blob: a4ef24e76cc7d9c7995f3413c48977ed96dc996b [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Lloyd Pique70d91362018-10-18 16:02:55 -070038#include <compositionengine/CompositionEngine.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080039#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070040#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070041#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070042#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080043#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080044#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080045#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070046#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070047#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070048#include <ui/ColorSpace.h>
49#include <ui/DebugUtils.h>
50#include <ui/DisplayInfo.h>
51#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070052#include <ui/GraphicBufferAllocator.h>
53#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <utils/String16.h>
57#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070060#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070077#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070078#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070080#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Steven Thomasb02664d2017-07-26 18:48:28 -070082#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070083#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070084#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070085#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070086#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070089#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070090#include "Scheduler/EventControlThread.h"
91#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070092#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070093#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070094#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080095#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070096
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070098
David Sodman7e4ae112018-02-09 15:02:28 -080099#include "android-base/stringprintf.h"
100
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900101#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800102#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700103#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800104#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900105#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106
chaviw1d044282017-09-27 12:19:28 -0700107#include <layerproto/LayerProtoParser.h>
108
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800109namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700110
Jaesoo Lee43518572017-01-23 19:03:16 +0900111using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900112using namespace android::hardware::configstore::V1_0;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800113using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700114using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700115using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700116using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700117using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118
Steven Thomasb02664d2017-07-26 18:48:28 -0700119namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700120
121#pragma clang diagnostic push
122#pragma clang diagnostic error "-Wswitch-enum"
123
124bool isWideColorMode(const ColorMode colorMode) {
125 switch (colorMode) {
126 case ColorMode::DISPLAY_P3:
127 case ColorMode::ADOBE_RGB:
128 case ColorMode::DCI_P3:
129 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700130 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700131 case ColorMode::BT2100_PQ:
132 case ColorMode::BT2100_HLG:
133 return true;
134 case ColorMode::NATIVE:
135 case ColorMode::STANDARD_BT601_625:
136 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
137 case ColorMode::STANDARD_BT601_525:
138 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
139 case ColorMode::STANDARD_BT709:
140 case ColorMode::SRGB:
141 return false;
142 }
143 return false;
144}
145
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700146ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
147 switch (rotation) {
148 case ISurfaceComposer::eRotateNone:
149 return ui::Transform::ROT_0;
150 case ISurfaceComposer::eRotate90:
151 return ui::Transform::ROT_90;
152 case ISurfaceComposer::eRotate180:
153 return ui::Transform::ROT_180;
154 case ISurfaceComposer::eRotate270:
155 return ui::Transform::ROT_270;
156 }
157 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
158 return ui::Transform::ROT_0;
159}
160
Peiyong Linfca547f2018-07-09 13:03:33 -0700161#pragma clang diagnostic pop
162
Steven Thomasb02664d2017-07-26 18:48:28 -0700163class ConditionalLock {
164public:
165 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
166 if (lock) {
167 mMutex.lock();
168 }
169 }
170 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
171private:
172 Mutex& mMutex;
173 bool mLocked;
174};
Peiyong Linfca547f2018-07-09 13:03:33 -0700175
Peiyong Lin9d846a52018-11-05 13:18:20 -0800176// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
177bool validateCompositionDataspace(Dataspace dataspace) {
178 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
179}
180
Steven Thomasb02664d2017-07-26 18:48:28 -0700181} // namespace anonymous
182
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800183// ---------------------------------------------------------------------------
184
Mathias Agopian99b49842011-06-27 16:05:52 -0700185const String16 sHardwareTest("android.permission.HARDWARE_TEST");
186const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
187const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
188const String16 sDump("android.permission.DUMP");
189
190// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800191int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
192int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700193int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700194bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800195uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800196bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800197bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800198int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600199bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700200int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700201bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700202bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700203Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
204ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
205Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
206ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700207
Kalle Raitaa099a242017-01-11 11:17:29 -0800208std::string getHwcServiceName() {
209 char value[PROPERTY_VALUE_MAX] = {};
210 property_get("debug.sf.hwc_service_name", value, "default");
211 ALOGI("Using HWComposer service: '%s'", value);
212 return std::string(value);
213}
214
215bool useTrebleTestingOverride() {
216 char value[PROPERTY_VALUE_MAX] = {};
217 property_get("debug.sf.treble_testing_override", value, "false");
218 ALOGI("Treble testing override: '%s'", value);
219 return std::string(value) == "true";
220}
221
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800222std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
223 switch(displayColorSetting) {
224 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700225 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800226 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700227 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800228 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700229 return std::string("Enhanced");
230 default:
231 return std::string("Unknown ") +
232 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800233 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800234}
235
David Sodmanbc815282017-11-05 18:57:52 -0800236SurfaceFlingerBE::SurfaceFlingerBE()
237 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800238 mFrameBuckets(),
239 mTotalTime(0),
240 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800241 mComposerSequenceId(0) {
242}
243
Lloyd Pique90c115d2018-09-18 21:39:42 -0700244SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
245 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800246 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700247 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700248 mTransactionPending(false),
249 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700250 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700251 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800254 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800255 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800256 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700258 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700259 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700260 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700261 mDebugInTransaction(0),
262 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700263 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800264 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700265 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700266 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800267 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800268 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800269 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700270 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700271 mMainThreadId(std::this_thread::get_id()),
272 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800273
Lloyd Pique90c115d2018-09-18 21:39:42 -0700274SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
275 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800276 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800277
278 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
280
281 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
283
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800284 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700287 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
289
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700290 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
292
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800293 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
295
Steven Thomas050b2c82017-03-06 11:45:16 -0800296 // Vr flinger is only enabled on Daydream ready devices.
297 useVrFlinger = getBool< ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::useVrFlinger>(false);
299
Fabien Sanglard1971b632017-03-10 14:50:03 -0800300 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
302
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600303 hasWideColorDisplay =
304 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700305 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700306 getBool<V1_2::ISurfaceFlingerConfigs,
307 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
308
309 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
310 if (surfaceFlingerConfigsServiceV1_2) {
311 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700312 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
313 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
314 defaultCompositionDataspace = tmpDefaultDataspace;
315 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
316 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
317 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
318 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700319 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800320 mDefaultCompositionDataspace = defaultCompositionDataspace;
321 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600322
Peiyong Linb3839ad2018-09-05 15:37:19 -0700323 useContextPriority = getBool<ISurfaceFlingerConfigs,
324 &ISurfaceFlingerConfigs::useContextPriority>(true);
325
Iris Chang7501ed62018-04-30 14:45:42 +0800326 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700327 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
328 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800329 V1_1::DisplayOrientation::ORIENTATION_0);
330
331 switch (primaryDisplayOrientation) {
332 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700333 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
335 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800340 break;
341 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
344 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800346
Lloyd Pique90c115d2018-09-18 21:39:42 -0700347 mPrimaryDispSync =
348 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
349 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351 // debugging stuff...
352 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700353
Mathias Agopianb4b17302013-03-20 18:36:41 -0700354 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700355 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700356
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800357 property_get("debug.sf.showupdates", value, "0");
358 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700359
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700360 property_get("debug.sf.ddms", value, "0");
361 mDebugDDMS = atoi(value);
362 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700363 if (!startDdmConnection()) {
364 // start failed, and DDMS debugging not enabled
365 mDebugDDMS = 0;
366 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700367 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700368 ALOGI_IF(mDebugRegion, "showupdates enabled");
369 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700370
371 property_get("debug.sf.disable_backpressure", value, "0");
372 mPropagateBackpressure = !atoi(value);
373 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700374
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800375 property_get("debug.sf.enable_hwc_vds", value, "0");
376 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800377 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800378
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800379 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800380 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800381 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700382
Yiwei Zhang243b3782018-05-15 17:40:04 -0700383 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700384 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
385 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
386
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200387 property_get("debug.sf.early_phase_offset_ns", value, "-1");
388 const int earlySfOffsetNs = atoi(value);
389
390 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
391 const int earlyGlSfOffsetNs = atoi(value);
392
393 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
394 const int earlyAppOffsetNs = atoi(value);
395
396 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
397 const int earlyGlAppOffsetNs = atoi(value);
398
Ana Krulec98b5b242018-08-10 15:03:23 -0700399 property_get("debug.sf.use_scheduler", value, "0");
400 mUseScheduler = atoi(value);
401
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200402 const VSyncModulator::Offsets earlyOffsets =
403 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
404 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
405 const VSyncModulator::Offsets earlyGlOffsets =
406 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
407 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
408 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
409 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700410
Romain Guy11d63f42017-07-20 12:47:14 -0700411 // We should be reading 'persist.sys.sf.color_saturation' here
412 // but since /data may be encrypted, we need to wait until after vold
413 // comes online to attempt to read the property. The property is
414 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800415
416 if (useTrebleTestingOverride()) {
417 // Without the override SurfaceFlinger cannot connect to HIDL
418 // services that are not listed in the manifests. Considered
419 // deriving the setting from the set service name, but it
420 // would be brittle if the name that's not 'default' is used
421 // for production purposes later on.
422 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
423 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426void SurfaceFlinger::onFirstRef()
427{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800428 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429}
430
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431SurfaceFlinger::~SurfaceFlinger()
432{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800433}
434
Dan Stozac7014012014-02-14 15:03:43 -0800435void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800436{
437 // the window manager died on us. prepare its eulogy.
438
Andy McFadden13a082e2012-08-24 10:16:42 -0700439 // restore initial conditions (default device unblank, etc)
440 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800441
442 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700443 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800444}
445
Robert Carr1db73f62016-12-21 12:58:51 -0800446static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700447 status_t err = client->initCheck();
448 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800449 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450 }
Robert Carr1db73f62016-12-21 12:58:51 -0800451 return nullptr;
452}
453
454sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
455 return initClient(new Client(this));
456}
457
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700458sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
459 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700460{
461 class DisplayToken : public BBinder {
462 sp<SurfaceFlinger> flinger;
463 virtual ~DisplayToken() {
464 // no more references, this display must be terminated
465 Mutex::Autolock _l(flinger->mStateLock);
466 flinger->mCurrentState.displays.removeItem(this);
467 flinger->setTransactionFlags(eDisplayTransactionNeeded);
468 }
469 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700470 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700471 : flinger(flinger) {
472 }
473 };
474
475 sp<BBinder> token = new DisplayToken(this);
476
477 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700478 // Display ID is assigned when virtual display is allocated by HWC.
479 DisplayDeviceState state;
480 state.isSecure = secure;
481 state.displayName = displayName;
482 mCurrentState.displays.add(token, state);
483 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700484 return token;
485}
486
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700487void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700488 Mutex::Autolock _l(mStateLock);
489
Dominik Laskowski075d3172018-05-24 15:50:06 -0700490 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
491 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700492 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700493 return;
494 }
495
Dominik Laskowski075d3172018-05-24 15:50:06 -0700496 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
497 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700498 ALOGE("destroyDisplay called for non-virtual display");
499 return;
500 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700501 mInterceptor->saveDisplayDeletion(state.sequenceId);
502 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700503 setTransactionFlags(eDisplayTransactionNeeded);
504}
505
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700507 std::optional<DisplayId> displayId;
508
509 if (id == HWC_DISPLAY_PRIMARY) {
510 displayId = getInternalDisplayId();
511 } else if (id == HWC_DISPLAY_EXTERNAL) {
512 displayId = getExternalDisplayId();
513 }
514
515 if (!displayId) {
516 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800517 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700518 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700519
520 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521}
522
Ady Abraham37965d42018-11-01 13:43:32 -0700523status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
524 if (!outGetColorManagement) {
525 return BAD_VALUE;
526 }
527 *outGetColorManagement = useColorManagement;
528 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700529}
530
Lloyd Pique441d5042018-10-18 16:49:51 -0700531HWComposer& SurfaceFlinger::getHwComposer() const {
532 return mCompositionEngine->getHwComposer();
533}
534
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700535renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
536 return mCompositionEngine->getRenderEngine();
537}
538
Lloyd Pique70d91362018-10-18 16:02:55 -0700539compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
540 return *mCompositionEngine.get();
541}
542
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800543void SurfaceFlinger::bootFinished()
544{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700545 if (mStartPropertySetThread->join() != NO_ERROR) {
546 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800547 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548 const nsecs_t now = systemTime();
549 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000550 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700551
552 // wait patiently for the window manager death
553 const String16 name("window");
554 sp<IBinder> window(defaultServiceManager()->getService(name));
555 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700556 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557 }
Robert Carr720e5062018-07-30 17:45:14 -0700558 sp<IBinder> input(defaultServiceManager()->getService(
559 String16("inputflinger")));
560 if (input == nullptr) {
561 ALOGE("Failed to link to input service");
562 } else {
563 mInputFlinger = interface_cast<IInputFlinger>(input);
564 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700565
Steven Thomas050b2c82017-03-06 11:45:16 -0800566 if (mVrFlinger) {
567 mVrFlinger->OnBootFinished();
568 }
569
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700570 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700571 // formerly we would just kill the process, but we now ask it to exit so it
572 // can choose where to stop the animation.
573 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700574
575 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
576 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
577 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700578
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800579 postMessageAsync(new LambdaMessage([this] {
580 readPersistentProperties();
581 mBootStage = BootStage::FINISHED;
582 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800583}
584
Dan Stoza436ccf32018-06-21 12:10:12 -0700585uint32_t SurfaceFlinger::getNewTexture() {
586 {
587 std::lock_guard lock(mTexturePoolMutex);
588 if (!mTexturePool.empty()) {
589 uint32_t name = mTexturePool.back();
590 mTexturePool.pop_back();
591 ATRACE_INT("TexturePoolSize", mTexturePool.size());
592 return name;
593 }
594
595 // The pool was too small, so increase it for the future
596 ++mTexturePoolSize;
597 }
598
599 // The pool was empty, so we need to get a new texture name directly using a
600 // blocking call to the main thread
601 uint32_t name = 0;
602 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
603 return name;
604}
605
Mathias Agopian3f844832013-08-07 21:24:32 -0700606void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700607 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700608}
609
Wei Wangf9b05ee2017-07-19 20:59:39 -0700610// Do not call property_set on main thread which will be blocked by init
611// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700612void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700613 ALOGI( "SurfaceFlinger's main thread ready to run. "
614 "Initializing graphics H/W...");
615
Thierry Strudel2924d012017-08-14 15:19:37 -0700616 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900617
Steven Thomasb02664d2017-07-26 18:48:28 -0700618 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800619
Steven Thomasb02664d2017-07-26 18:48:28 -0700620 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700621 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700622 mScheduler = getFactory().createScheduler([this](bool enabled) {
623 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
624 });
625
Ana Krulec98b5b242018-08-10 15:03:23 -0700626 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700627 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700628 [this] { resyncWithRateLimit(); },
629 impl::EventThread::InterceptVSyncsCallback());
630 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700631 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700632 [this] { resyncWithRateLimit(); },
633 [this](nsecs_t timestamp) {
634 mInterceptor->saveVSyncEvent(timestamp);
635 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800636
Ana Krulec98b5b242018-08-10 15:03:23 -0700637 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700638 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
639 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700640 } else {
641 mEventThreadSource =
642 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
643 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
644 mEventThread =
645 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
646 [this] { resyncWithRateLimit(); },
647 impl::EventThread::InterceptVSyncsCallback(),
648 "appEventThread");
649 mSfEventThreadSource =
650 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
651 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
652
653 mSFEventThread =
654 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
655 [this] { resyncWithRateLimit(); },
656 [this](nsecs_t timestamp) {
657 mInterceptor->saveVSyncEvent(timestamp);
658 },
659 "sfEventThread");
660 mEventQueue->setEventThread(mSFEventThread.get());
661 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
662 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800663
Steven Thomasb02664d2017-07-26 18:48:28 -0700664 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700665 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700666 renderEngineFeature |= (useColorManagement ?
667 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700668 renderEngineFeature |= (useContextPriority ?
669 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700670
671 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700672 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700673 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700674 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700675
676 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
677 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700678 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
679 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800680 // Process any initial hotplug and resulting display changes.
681 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700682 const auto display = getDefaultDisplayDeviceLocked();
683 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700684 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700685 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800686
Steven Thomas050b2c82017-03-06 11:45:16 -0800687 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700688 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700689 // This callback is called from the vr flinger dispatch thread. We
690 // need to call signalTransaction(), which requires holding
691 // mStateLock when we're not on the main thread. Acquiring
692 // mStateLock from the vr flinger dispatch thread might trigger a
693 // deadlock in surface flinger (see b/66916578), so post a message
694 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700695 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700696 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
697 mVrFlingerRequestsDisplay = requestDisplay;
698 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700699 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800700 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700701 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
702 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700703 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700704 .value_or(0),
705 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800706 if (!mVrFlinger) {
707 ALOGE("Failed to start vrflinger");
708 }
709 }
710
Lloyd Pique90c115d2018-09-18 21:39:42 -0700711 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700712 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700713
Mathias Agopian92a979a2012-08-02 18:32:23 -0700714 // initialize our drawing state
715 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700716
Andy McFadden13a082e2012-08-24 10:16:42 -0700717 // set initial conditions (e.g. unblank default device)
718 initializeDisplays();
719
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700720 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700721
Wei Wangf9b05ee2017-07-19 20:59:39 -0700722 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700723
724 const bool presentFenceReliable =
725 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
726 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700727
728 if (mStartPropertySetThread->Start() != NO_ERROR) {
729 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800730 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800731
Ana Krulec7d1d6832018-12-27 11:10:09 -0800732 if (mUseScheduler) {
733 mScheduler->setExpiredIdleTimerCallback([this]() { setRefreshRateTo(60.f /* fps */); });
734 mScheduler->setResetIdleTimerCallback([this]() { setRefreshRateTo(90.f /* fps */); });
735 }
736
Dan Stoza9e56aa02015-11-02 13:00:03 -0800737 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700738}
739
Romain Guy11d63f42017-07-20 12:47:14 -0700740void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700741 Mutex::Autolock _l(mStateLock);
742
Romain Guy11d63f42017-07-20 12:47:14 -0700743 char value[PROPERTY_VALUE_MAX];
744
745 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800746 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700747 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800748 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100749
750 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700751 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700752}
753
Mathias Agopiana67e4182012-06-19 17:26:12 -0700754void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800755 // Start boot animation service by setting a property mailbox
756 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700757 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800758 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700759 if (mStartPropertySetThread->join() != NO_ERROR) {
760 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800761 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700762}
763
Mathias Agopian875d8e12013-06-07 15:35:48 -0700764size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700765 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700766}
767
Mathias Agopian875d8e12013-06-07 15:35:48 -0700768size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700769 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700770}
771
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800772// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800773
Jamie Gennis582270d2011-08-17 18:19:00 -0700774bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800775 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800776 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800777 return authenticateSurfaceTextureLocked(bufferProducer);
778}
779
780bool SurfaceFlinger::authenticateSurfaceTextureLocked(
781 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800782 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800783 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800784}
785
Brian Anderson6b376712017-04-04 10:51:39 -0700786status_t SurfaceFlinger::getSupportedFrameTimestamps(
787 std::vector<FrameEvent>* outSupported) const {
788 *outSupported = {
789 FrameEvent::REQUESTED_PRESENT,
790 FrameEvent::ACQUIRE,
791 FrameEvent::LATCH,
792 FrameEvent::FIRST_REFRESH_START,
793 FrameEvent::LAST_REFRESH_START,
794 FrameEvent::GPU_COMPOSITION_DONE,
795 FrameEvent::DEQUEUE_READY,
796 FrameEvent::RELEASE,
797 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700798 ConditionalLock _l(mStateLock,
799 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700800 if (!getHwComposer().hasCapability(
801 HWC2::Capability::PresentFenceIsNotReliable)) {
802 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
803 }
804 return NO_ERROR;
805}
806
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700807status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
808 Vector<DisplayInfo>* configs) {
809 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700810 return BAD_VALUE;
811 }
812
Dominik Laskowski075d3172018-05-24 15:50:06 -0700813 const auto displayId = getPhysicalDisplayId(displayToken);
814 if (!displayId) {
815 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700816 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 // TODO: Not sure if display density should handled by SF any longer
819 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700820 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700822 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800823 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700824 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825 }
826 return density;
827 }
828 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700829 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700831 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 return getDensityFromProperty("ro.sf.lcd_density"); }
833 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700834
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700836
Steven Thomas6d8110b2017-08-31 18:24:21 -0700837 ConditionalLock _l(mStateLock,
838 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700839 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700840 DisplayInfo info = DisplayInfo();
841
Dan Stoza9e56aa02015-11-02 13:00:03 -0800842 float xdpi = hwConfig->getDpiX();
843 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700844
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700845 info.w = hwConfig->getWidth();
846 info.h = hwConfig->getHeight();
847 // Default display viewport to display width and height
848 info.viewportW = info.w;
849 info.viewportH = info.h;
850
Dominik Laskowski075d3172018-05-24 15:50:06 -0700851 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 // The density of the device is provided by a build property
853 float density = Density::getBuildDensity() / 160.0f;
854 if (density == 0) {
855 // the build doesn't provide a density -- this is wrong!
856 // use xdpi instead
857 ALOGE("ro.sf.lcd_density must be defined as a build property");
858 density = xdpi / 160.0f;
859 }
860 if (Density::getEmuDensity()) {
861 // if "qemu.sf.lcd_density" is specified, it overrides everything
862 xdpi = ydpi = density = Density::getEmuDensity();
863 density /= 160.0f;
864 }
865 info.density = density;
866
867 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700868 const auto display = getDefaultDisplayDeviceLocked();
869 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700870
871 // This is for screenrecord
872 const Rect viewport = display->getViewport();
873 if (viewport.isValid()) {
874 info.viewportW = uint32_t(viewport.getWidth());
875 info.viewportH = uint32_t(viewport.getHeight());
876 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700877 } else {
878 // TODO: where should this value come from?
879 static const int TV_DENSITY = 213;
880 info.density = TV_DENSITY / 160.0f;
881 info.orientation = 0;
882 }
883
Dan Stoza7f7da322014-05-02 15:26:25 -0700884 info.xdpi = xdpi;
885 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900887 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888
Andy McFadden91b2ca82014-06-13 14:04:23 -0700889 // This is how far in advance a buffer must be queued for
890 // presentation at a given time. If you want a buffer to appear
891 // on the screen at time N, you must submit the buffer before
892 // (N - presentationDeadline).
893 //
894 // Normally it's one full refresh period (to give SF a chance to
895 // latch the buffer), but this can be reduced by configuring a
896 // DispSync offset. Any additional delays introduced by the hardware
897 // composer or panel must be accounted for here.
898 //
899 // We add an additional 1ms to allow for processing time and
900 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800901 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800902 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700903
904 // All non-virtual displays are currently considered secure.
905 info.secure = true;
906
Dominik Laskowski075d3172018-05-24 15:50:06 -0700907 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700908 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800909 std::swap(info.w, info.h);
910 }
911
Michael Wright28f24d02016-07-12 13:30:53 -0700912 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700913 }
914
Dan Stoza7f7da322014-05-02 15:26:25 -0700915 return NO_ERROR;
916}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
919 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700920 return BAD_VALUE;
921 }
922
Ana Krulece588e312018-09-18 12:32:24 -0700923 if (mUseScheduler) {
924 mScheduler->getDisplayStatInfo(stats);
925 } else {
926 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
927 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
928 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700929 return NO_ERROR;
930}
931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
933 const auto display = getDisplayDevice(displayToken);
934 if (!display) {
935 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800936 return BAD_VALUE;
937 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700938
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700939 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700940}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700941
Ana Krulec7d1d6832018-12-27 11:10:09 -0800942status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
943 ATRACE_NAME("setActiveConfigAsync");
944 postMessageAsync(new LambdaMessage([=] { setActiveConfigInternal(displayToken, mode); }));
945 return NO_ERROR;
946}
947
948status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
949 ATRACE_NAME("setActiveConfigSync");
950 postMessageSync(new LambdaMessage([&] { setActiveConfigInternal(displayToken, mode); }));
951 return NO_ERROR;
952}
953
954void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
955 Vector<DisplayInfo> configs;
956 getDisplayConfigs(displayToken, &configs);
957 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
958 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
959 return;
960 }
961
962 const auto display = getDisplayDevice(displayToken);
963 if (!display) {
964 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
965 displayToken.get());
966 return;
967 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700968 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800969 ALOGW("Attempt to set active config %d for virtual display", mode);
970 return;
971 }
972 int currentDisplayPowerMode = display->getPowerMode();
973 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
974 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700975 return;
976 }
977
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700978 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700979 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800980 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700981 return;
982 }
983
Dominik Laskowski075d3172018-05-24 15:50:06 -0700984 const auto displayId = display->getId();
985 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700986
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700987 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700988 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700989
Ana Krulec7d1d6832018-12-27 11:10:09 -0800990 ATRACE_INT("ActiveConfigMode", mode);
991 resyncToHardwareVsync(true);
Mathias Agopianc666cae2012-07-25 18:56:13 -0700992}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700993
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700994status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
995 Vector<ColorMode>* outColorModes) {
996 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700997 return BAD_VALUE;
998 }
999
Dominik Laskowski075d3172018-05-24 15:50:06 -07001000 const auto displayId = getPhysicalDisplayId(displayToken);
1001 if (!displayId) {
1002 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001003 }
1004
Peiyong Lina52f0292018-03-14 17:26:31 -07001005 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001006 {
1007 ConditionalLock _l(mStateLock,
1008 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001009 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001010 }
Michael Wright28f24d02016-07-12 13:30:53 -07001011 outColorModes->clear();
1012 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1013
1014 return NO_ERROR;
1015}
1016
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001017ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1018 if (const auto display = getDisplayDevice(displayToken)) {
1019 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001020 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001021 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001022}
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1025 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001026 if (display->isVirtual()) {
1027 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1028 return;
1029 }
1030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031 ColorMode currentMode = display->getActiveColorMode();
1032 Dataspace currentDataSpace = display->getCompositionDataSpace();
1033 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001034
Peiyong Lin38e9a562018-04-10 16:24:20 -07001035 if (mode == currentMode && dataSpace == currentDataSpace &&
1036 renderIntent == currentRenderIntent) {
1037 return;
1038 }
1039
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001040 display->setActiveColorMode(mode);
1041 display->setCompositionDataSpace(dataSpace);
1042 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001043
Dominik Laskowski075d3172018-05-24 15:50:06 -07001044 const auto displayId = display->getId();
1045 LOG_ALWAYS_FATAL_IF(!displayId);
1046 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1047
Dominik Laskowski34157762018-10-31 13:07:19 -07001048 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001049 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001050 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001051}
1052
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001053status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001054 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055 Vector<ColorMode> modes;
1056 getDisplayColorModes(displayToken, &modes);
1057 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1058 if (mode < ColorMode::NATIVE || !exists) {
1059 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1060 decodeColorMode(mode).c_str(), mode, displayToken.get());
1061 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001062 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001063 const auto display = getDisplayDevice(displayToken);
1064 if (!display) {
1065 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1066 decodeColorMode(mode).c_str(), mode, displayToken.get());
1067 } else if (display->isVirtual()) {
1068 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1069 decodeColorMode(mode).c_str(), mode);
1070 } else {
1071 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1072 RenderIntent::COLORIMETRIC);
1073 }
1074 }));
1075
Michael Wright28f24d02016-07-12 13:30:53 -07001076 return NO_ERROR;
1077}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001078
Svetoslavd85084b2014-03-20 10:28:31 -07001079status_t SurfaceFlinger::clearAnimationFrameStats() {
1080 Mutex::Autolock _l(mStateLock);
1081 mAnimFrameTracker.clearStats();
1082 return NO_ERROR;
1083}
1084
1085status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1086 Mutex::Autolock _l(mStateLock);
1087 mAnimFrameTracker.getStats(outStats);
1088 return NO_ERROR;
1089}
1090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001091status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1092 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001093 Mutex::Autolock _l(mStateLock);
1094
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001095 const auto display = getDisplayDeviceLocked(displayToken);
1096 if (!display) {
1097 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001098 return BAD_VALUE;
1099 }
1100
Peiyong Linfb069302018-04-25 14:34:31 -07001101 // At this point the DisplayDeivce should already be set up,
1102 // meaning the luminance information is already queried from
1103 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001104 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001105 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1106 capabilities.getDesiredMaxLuminance(),
1107 capabilities.getDesiredMaxAverageLuminance(),
1108 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001109
1110 return NO_ERROR;
1111}
1112
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001113status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1114 ui::PixelFormat* outFormat,
1115 ui::Dataspace* outDataspace,
1116 uint8_t* outComponentMask) const {
1117 if (!outFormat || !outDataspace || !outComponentMask) {
1118 return BAD_VALUE;
1119 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001120 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001121 if (!display || !display->getId()) {
1122 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1123 return BAD_VALUE;
1124 }
1125 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1126 outDataspace, outComponentMask);
1127}
1128
Kevin DuBois74e53772018-11-19 10:52:38 -08001129status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1130 bool enable, uint8_t componentMask,
1131 uint64_t maxFrames) const {
1132 const auto display = getDisplayDevice(displayToken);
1133 if (!display || !display->getId()) {
1134 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1135 return BAD_VALUE;
1136 }
1137
1138 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1139 componentMask, maxFrames);
1140}
1141
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001142status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1143 uint64_t maxFrames, uint64_t timestamp,
1144 DisplayedFrameStats* outStats) const {
1145 const auto display = getDisplayDevice(displayToken);
1146 if (!display || !display->getId()) {
1147 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1148 return BAD_VALUE;
1149 }
1150
1151 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1152 outStats);
1153}
1154
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001155status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001156 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001157 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001158
Chia-I Wu90f669f2017-10-05 14:24:41 -07001159 if (mInjectVSyncs == enable) {
1160 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001161 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001162
Ana Krulec98b5b242018-08-10 15:03:23 -07001163 // TODO(akrulec): Part of the Injector should be refactored, so that it
1164 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001165 if (enable) {
1166 ALOGV("VSync Injections enabled");
1167 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001168 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001169 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001170 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001171 impl::EventThread::InterceptVSyncsCallback(),
1172 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001173 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001174 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001175 } else {
1176 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001177 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001178 }
1179
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001180 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001181 }));
1182
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001183 return NO_ERROR;
1184}
1185
1186status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001187 Mutex::Autolock _l(mStateLock);
1188
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001189 if (!mInjectVSyncs) {
1190 ALOGE("VSync Injections not enabled");
1191 return BAD_VALUE;
1192 }
1193 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1194 ALOGV("Injecting VSync inside SurfaceFlinger");
1195 mVSyncInjector->onInjectSyncEvent(when);
1196 }
1197 return NO_ERROR;
1198}
1199
Lloyd Pique755e3192018-01-31 16:46:15 -08001200status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1201 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001202 // Try to acquire a lock for 1s, fail gracefully
1203 const status_t err = mStateLock.timedLock(s2ns(1));
1204 const bool locked = (err == NO_ERROR);
1205 if (!locked) {
1206 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1207 return TIMED_OUT;
1208 }
1209
1210 outLayers->clear();
1211 mCurrentState.traverseInZOrder([&](Layer* layer) {
1212 outLayers->push_back(layer->getLayerDebugInfo());
1213 });
1214
1215 mStateLock.unlock();
1216 return NO_ERROR;
1217}
1218
Peiyong Linc6780972018-10-28 15:24:08 -07001219status_t SurfaceFlinger::getCompositionPreference(
1220 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1221 Dataspace* outWideColorGamutDataspace,
1222 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001223 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001224 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001225 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001226 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001227 return NO_ERROR;
1228}
1229
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001230// ----------------------------------------------------------------------------
1231
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001232sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1233 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001234 if (mUseScheduler) {
1235 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1236 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1237 } else {
1238 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1239 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001240 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001241 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1242 return mSFEventThread->createEventConnection();
1243 } else {
1244 return mEventThread->createEventConnection();
1245 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001246 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001247}
1248
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001249// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001250
1251void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001252 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001253}
1254
1255void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001256 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001257}
1258
1259void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001260 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001261}
1262
1263void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001264 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001265 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001266}
1267
1268status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001269 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001270 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001271}
1272
1273status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001274 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001275 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001276 if (res == NO_ERROR) {
1277 msg->wait();
1278 }
1279 return res;
1280}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001281
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001282void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001283 do {
1284 waitForEvent();
1285 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001286}
1287
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288void SurfaceFlinger::enableHardwareVsync() {
1289 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001290 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001291 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001292 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001293 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001294 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001295}
1296
Jesse Hall948fe0c2013-10-14 12:56:09 -07001297void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001298 Mutex::Autolock _l(mHWVsyncLock);
1299
Jesse Hall948fe0c2013-10-14 12:56:09 -07001300 if (makeAvailable) {
1301 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001302 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1303 if (mUseScheduler) {
1304 mScheduler->makeHWSyncAvailable(true);
1305 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001306 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001307 // Hardware vsync is not currently available, so abort the resync
1308 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001309 return;
1310 }
1311
Dominik Laskowski075d3172018-05-24 15:50:06 -07001312 const auto displayId = getInternalDisplayId();
1313 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001314 return;
1315 }
1316
Dominik Laskowski075d3172018-05-24 15:50:06 -07001317 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001318 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001319
Ana Krulece588e312018-09-18 12:32:24 -07001320 if (mUseScheduler) {
1321 mScheduler->setVsyncPeriod(period);
1322 } else {
1323 mPrimaryDispSync->reset();
1324 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001325
Ana Krulece588e312018-09-18 12:32:24 -07001326 if (!mPrimaryHWVsyncEnabled) {
1327 mPrimaryDispSync->beginResync();
1328 mEventControlThread->setVsyncEnabled(true);
1329 mPrimaryHWVsyncEnabled = true;
1330 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001331 }
1332}
1333
Jesse Hall948fe0c2013-10-14 12:56:09 -07001334void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001335 Mutex::Autolock _l(mHWVsyncLock);
1336 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001337 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001338 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001339 mPrimaryHWVsyncEnabled = false;
1340 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001341 if (makeUnavailable) {
1342 mHWVsyncAvailable = false;
1343 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001344}
1345
Tim Murray4a4e4a22016-04-19 16:29:23 +00001346void SurfaceFlinger::resyncWithRateLimit() {
1347 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001348
1349 // No explicit locking is needed here since EventThread holds a lock while calling this method
1350 static nsecs_t sLastResyncAttempted = 0;
1351 const nsecs_t now = systemTime();
1352 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001353 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001354 }
Dan Stoza57164302017-05-08 14:03:54 -07001355 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001356}
1357
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001358void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1359 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001360 ATRACE_NAME("SF onVsync");
1361
Steven Thomas3cfac282017-02-06 12:29:30 -08001362 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001363 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001364 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001365 return;
1366 }
1367
Dominik Laskowski075d3172018-05-24 15:50:06 -07001368 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001369 return;
1370 }
1371
Dominik Laskowski075d3172018-05-24 15:50:06 -07001372 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001373 // For now, we don't do anything with external display vsyncs.
1374 return;
1375 }
1376
Ana Krulece588e312018-09-18 12:32:24 -07001377 if (mUseScheduler) {
1378 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001379 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001380 bool needsHwVsync = false;
1381 { // Scope for the lock
1382 Mutex::Autolock _l(mHWVsyncLock);
1383 if (mPrimaryHWVsyncEnabled) {
1384 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1385 }
1386 }
1387
1388 if (needsHwVsync) {
1389 enableHardwareVsync();
1390 } else {
1391 disableHardwareVsync(false);
1392 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001393 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001394}
1395
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001396void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001397 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1398 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001399}
1400
Ana Krulec7d1d6832018-12-27 11:10:09 -08001401void SurfaceFlinger::setRefreshRateTo(float newFps) {
1402 const auto displayId = getInternalDisplayId();
1403 if (!displayId || mBootStage != BootStage::FINISHED) {
1404 return;
1405 }
1406 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1407 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1408 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1409 // refresh cycle.
1410
1411 // Don't do any updating if the current fps is the same as the new one.
1412 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1413 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1414 if (currentVsyncPeriod == 0) {
1415 return;
1416 }
1417 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1418 // floating numbers.
1419 const float currentFps = 1e9 / currentVsyncPeriod;
1420 if (std::abs(currentFps - newFps) <= 1) {
1421 return;
1422 }
1423
1424 auto configs = getHwComposer().getConfigs(*displayId);
1425 for (int i = 0; i < configs.size(); i++) {
1426 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1427 if (vsyncPeriod == 0) {
1428 continue;
1429 }
1430 const float fps = 1e9 / vsyncPeriod;
1431 // TODO(b/113612090): There should be a better way at determining which config
1432 // has the right refresh rate.
1433 if (std::abs(fps - newFps) <= 1) {
1434 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1435 if (!display) return;
1436 // This is posted in async function to avoid deadlock when getDisplayDevice
1437 // requires mStateLock.
1438 setActiveConfigAsync(display, i);
1439 ATRACE_INT("FPS", newFps);
1440 }
1441 }
1442}
1443
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001444void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001445 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001446 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001447 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001448
Lloyd Piqueba04e622017-12-14 17:11:26 -08001449 // Ignore events that do not have the right sequenceId.
1450 if (sequenceId != getBE().mComposerSequenceId) {
1451 return;
1452 }
1453
Steven Thomasb02664d2017-07-26 18:48:28 -07001454 // Only lock if we're not on the main thread. This function is normally
1455 // called on a hwbinder thread, but for the primary display it's called on
1456 // the main thread with the state lock already held, so don't attempt to
1457 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001458 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001459
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001460 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001461
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001462 if (std::this_thread::get_id() == mMainThreadId) {
1463 // Process all pending hot plug events immediately if we are on the main thread.
1464 processDisplayHotplugEventsLocked();
1465 }
1466
Lloyd Piqueba04e622017-12-14 17:11:26 -08001467 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001468}
1469
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001470void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001471 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001472 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001473 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001474 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001475 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001476}
1477
Dominik Laskowski075d3172018-05-24 15:50:06 -07001478void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001479 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001480 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001481 if (const auto displayId = getInternalDisplayId()) {
1482 getHwComposer().setVsyncEnabled(*displayId,
1483 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1484 }
Mathias Agopian86303202012-07-24 22:46:10 -07001485}
1486
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001487// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001488void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001489 if (mUseScheduler) {
1490 mScheduler->disableHardwareVsync(true);
1491 } else {
1492 disableHardwareVsync(true);
1493 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001494 // Clear the drawing state so that the logic inside of
1495 // handleTransactionLocked will fire. It will determine the delta between
1496 // mCurrentState and mDrawingState and re-apply all changes when we make the
1497 // transition.
1498 mDrawingState.displays.clear();
1499 mDisplays.clear();
1500}
1501
Steven Thomas050b2c82017-03-06 11:45:16 -08001502void SurfaceFlinger::updateVrFlinger() {
1503 if (!mVrFlinger)
1504 return;
1505 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001506 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001507 return;
1508 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001509
Lloyd Pique441d5042018-10-18 16:49:51 -07001510 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001511 ALOGE("Vr flinger is only supported for remote hardware composer"
1512 " service connections. Ignoring request to transition to vr"
1513 " flinger.");
1514 mVrFlingerRequestsDisplay = false;
1515 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001516 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001517
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001518 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001519
Steven Thomas0123ac62018-07-12 11:32:34 -07001520 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001521 LOG_ALWAYS_FATAL_IF(!display);
1522 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001523 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1524 // called below. Clear the reference now so we don't accidentally use it
1525 // later.
1526 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001527
Steven Thomasb02664d2017-07-26 18:48:28 -07001528 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001529 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001530 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001531
Steven Thomasb02664d2017-07-26 18:48:28 -07001532 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001533 // Delete the current instance before creating the new one
1534 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1535 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1536 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1537 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001538
Lloyd Pique441d5042018-10-18 16:49:51 -07001539 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001540 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001541
1542 if (vrFlingerRequestsDisplay) {
1543 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001544 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001545
1546 mVisibleRegionsDirty = true;
1547 invalidateHwcGeometry();
1548
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001549 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001550 display = getDefaultDisplayDeviceLocked();
1551 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001552 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001553
Steven Thomasb02664d2017-07-26 18:48:28 -07001554 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001555 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001556 const nsecs_t period = activeConfig->getVsyncPeriod();
1557 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001558
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001559 // The present fences returned from vr_hwc are not an accurate
1560 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001561 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001562 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1563 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001564 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001565 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001566 !hasSyncFramework);
1567 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001568
Steven Thomasb02664d2017-07-26 18:48:28 -07001569 // Use phase of 0 since phase is not known.
1570 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001571 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1572 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001573
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001574 resyncToHardwareVsync(false);
1575
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001576 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001577 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001578}
1579
Mathias Agopian4fec8732012-06-29 14:12:52 -07001580void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001581 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001582 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001583 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001584 if (mUseScheduler) {
1585 // This call is made each time SF wakes up and creates a new frame.
1586 mScheduler->incrementFrameCounter();
1587 }
Dan Stoza50182882016-07-08 12:02:20 -07001588 bool frameMissed = !mHadClientComposition &&
1589 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001590 (mPreviousPresentFence->getSignalTime() ==
1591 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001592 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001593 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001594 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001595 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001596 if (mPropagateBackpressure) {
1597 signalLayerUpdate();
1598 break;
1599 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001600 }
Dan Stoza50182882016-07-08 12:02:20 -07001601
Steven Thomas050b2c82017-03-06 11:45:16 -08001602 // Now that we're going to make it to the handleMessageTransaction()
1603 // call below it's safe to call updateVrFlinger(), which will
1604 // potentially trigger a display handoff.
1605 updateVrFlinger();
1606
Dan Stoza6b9454d2014-11-07 16:00:59 -08001607 bool refreshNeeded = handleMessageTransaction();
1608 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001609 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001610 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001611 // Signal a refresh if a transaction modified the window state,
1612 // a new buffer was latched, or if HWC has requested a full
1613 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001614 signalRefresh();
1615 }
1616 break;
1617 }
1618 case MessageQueue::REFRESH: {
1619 handleMessageRefresh();
1620 break;
1621 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001622 }
1623}
1624
Dan Stoza6b9454d2014-11-07 16:00:59 -08001625bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001626 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001627
1628 // Apply any ready transactions in the queues if there are still transactions that have not been
1629 // applied, wake up during the next vsync period and check again
1630 bool transactionNeeded = false;
1631 if (!flushTransactionQueues()) {
1632 transactionNeeded = true;
1633 }
1634
Mathias Agopian4fec8732012-06-29 14:12:52 -07001635 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001636 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001637 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001638
1639 if (transactionNeeded) {
1640 setTransactionFlags(eTransactionNeeded);
1641 }
1642
1643 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001644}
1645
Mathias Agopian4fec8732012-06-29 14:12:52 -07001646void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001647 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001648
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001649 mRefreshPending = false;
1650
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001651 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001652 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001653 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001654 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001655 for (const auto& [token, display] : mDisplays) {
1656 beginFrame(display);
1657 prepareFrame(display);
1658 doDebugFlashRegions(display, repaintEverything);
1659 doComposition(display, repaintEverything);
1660 }
1661
Adrian Roos1e1a1282017-11-01 19:05:31 +01001662 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001663 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001664
1665 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001666 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001667
Dan Stozabfbffeb2016-07-21 14:49:33 -07001668 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001669 for (const auto& [token, display] : mDisplays) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001670 mHadClientComposition =
1671 mHadClientComposition || getHwComposer().hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001672 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001673
Alec Mouri86770e52018-09-24 22:40:58 +00001674 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001675 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001676 if (mHadClientComposition) {
1677 base::unique_fd flushFence(getRenderEngine().flush());
1678 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1679 getBE().flushFence = new Fence(std::move(flushFence));
1680 } else {
1681 // Cleanup for hygiene.
1682 getBE().flushFence = Fence::NO_FENCE;
1683 }
1684 }
1685
Jorim Jaggi90535212018-05-23 23:44:06 +02001686 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001687
David Sodman7e4ae112018-02-09 15:02:28 -08001688 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001689 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001690 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001691 compositionInfo.hwc.hwcLayer = nullptr;
1692 }
David Sodmanba340492018-08-05 21:51:33 -07001693 }
David Sodman7e4ae112018-02-09 15:02:28 -08001694
1695 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001696}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001697
David Sodmanfa9b2af2017-12-24 13:28:59 -08001698
1699bool SurfaceFlinger::handleMessageInvalidate() {
1700 ATRACE_CALL();
1701 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001702}
1703
David Sodman79bba0e2018-08-05 18:07:49 -07001704void SurfaceFlinger::calculateWorkingSet() {
1705 ATRACE_CALL();
1706 ALOGV(__FUNCTION__);
1707
David Sodman79bba0e2018-08-05 18:07:49 -07001708 // build the h/w work list
1709 if (CC_UNLIKELY(mGeometryInvalid)) {
1710 mGeometryInvalid = false;
1711 for (const auto& [token, display] : mDisplays) {
1712 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001713 if (!displayId) {
1714 continue;
1715 }
David Sodman79bba0e2018-08-05 18:07:49 -07001716
Dominik Laskowski075d3172018-05-24 15:50:06 -07001717 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1718 for (size_t i = 0; i < currentLayers.size(); i++) {
1719 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001720
Dominik Laskowski075d3172018-05-24 15:50:06 -07001721 if (!layer->hasHwcLayer(*displayId)) {
1722 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1723 layer->forceClientComposition(*displayId);
1724 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001725 }
1726 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001727
1728 layer->setGeometry(display, i);
1729 if (mDebugDisableHWC || mDebugRegion) {
1730 layer->forceClientComposition(*displayId);
1731 }
David Sodman79bba0e2018-08-05 18:07:49 -07001732 }
1733 }
1734 }
1735
1736 // Set the per-frame data
1737 for (const auto& [token, display] : mDisplays) {
1738 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001739 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001740 continue;
1741 }
1742
1743 if (mDrawingState.colorMatrixChanged) {
1744 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001745 status_t result =
1746 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001747 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1748 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001749 }
1750 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1751 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001752 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001753 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1754 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1755 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001756 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001757 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1758 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1759 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001760 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001761 }
1762
Peiyong Lind3788632018-09-18 16:01:31 -07001763 // TODO(b/111562338) remove when composer 2.3 is shipped.
1764 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001765 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001766 }
1767
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001768 if (layer->getRoundedCornerState().radius > 0.0f) {
1769 layer->forceClientComposition(*displayId);
1770 }
1771
Dominik Laskowski075d3172018-05-24 15:50:06 -07001772 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001773 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001774 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001775 continue;
1776 }
1777
Dominik Laskowski075d3172018-05-24 15:50:06 -07001778 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1779 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001780 }
1781
Peiyong Lin13effd12018-07-24 17:01:47 -07001782 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001783 ColorMode colorMode;
1784 Dataspace dataSpace;
1785 RenderIntent renderIntent;
1786 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1787 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1788 }
1789 }
1790
1791 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001792
1793 for (const auto& [token, display] : mDisplays) {
1794 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001795 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001796 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001797
1798 if (displayId) {
1799 if (!layer->setHwcLayer(*displayId)) {
1800 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1801 }
1802 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001803 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001804
Dominik Laskowski05275f12018-11-01 15:03:24 -07001805 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001806 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1807 }
1808 }
David Sodman79bba0e2018-08-05 18:07:49 -07001809}
1810
David Sodmanfa9b2af2017-12-24 13:28:59 -08001811void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001812{
1813 // is debugging enabled
1814 if (CC_LIKELY(!mDebugRegion))
1815 return;
1816
David Sodmanfa9b2af2017-12-24 13:28:59 -08001817 if (display->isPoweredOn()) {
1818 // transform the dirty region into this screen's coordinate space
1819 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1820 if (!dirtyRegion.isEmpty()) {
1821 // redraw the whole screen
1822 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001823
David Sodmanfa9b2af2017-12-24 13:28:59 -08001824 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001825 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001826 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001827
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001828 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001829 }
1830 }
1831
David Sodmanfa9b2af2017-12-24 13:28:59 -08001832 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001833
1834 if (mDebugRegion > 1) {
1835 usleep(mDebugRegion * 1000);
1836 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001837
Dominik Laskowski05275f12018-11-01 15:03:24 -07001838 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001839}
1840
Adrian Roos1e1a1282017-11-01 19:05:31 +01001841void SurfaceFlinger::doTracing(const char* where) {
1842 ATRACE_CALL();
1843 ATRACE_NAME(where);
1844 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001845 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001846 }
1847}
1848
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001849void SurfaceFlinger::logLayerStats() {
1850 ATRACE_CALL();
1851 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001852 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001853 if (display->isPrimary()) {
1854 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001855 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001856 }
1857 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001858
1859 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001860 }
1861}
1862
David Sodman2b406362017-12-15 13:33:47 -08001863void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001865 ATRACE_CALL();
1866 ALOGV("preComposition");
1867
David Sodman2b406362017-12-15 13:33:47 -08001868 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1869
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001871 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001872 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001873 needExtraInvalidate = true;
1874 }
Robert Carr2047fae2016-11-28 14:09:09 -08001875 });
1876
Mathias Agopiancd60f992012-08-16 16:28:27 -07001877 if (needExtraInvalidate) {
1878 signalLayerUpdate();
1879 }
1880}
1881
Ana Krulece588e312018-09-18 12:32:24 -07001882void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1883 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001884 // Update queue of past composite+present times and determine the
1885 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001886 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001887 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001888 while (!getBE().mCompositePresentTimes.empty()) {
1889 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001890 // Cached values should have been updated before calling this method,
1891 // which helps avoid duplicate syscalls.
1892 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1893 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1894 break;
1895 }
1896 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001897 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001898 }
1899
1900 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001901 while (getBE().mCompositePresentTimes.size() > 16) {
1902 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001903 }
1904
Ana Krulece588e312018-09-18 12:32:24 -07001905 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001906}
1907
Ana Krulece588e312018-09-18 12:32:24 -07001908void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1909 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001910 // Integer division and modulo round toward 0 not -inf, so we need to
1911 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001912 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1913 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1914 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001915
Brian Andersond0010582017-03-07 13:20:31 -08001916 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1917 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001918 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001919 }
1920
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001921 // Snap the latency to a value that removes scheduling jitter from the
1922 // composition and present times, which often have >1ms of jitter.
1923 // Reducing jitter is important if an app attempts to extrapolate
1924 // something (such as user input) to an accurate diasplay time.
1925 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1926 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001927 nsecs_t bias = stats.vsyncPeriod / 2;
1928 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1929 nsecs_t snappedCompositeToPresentLatency =
1930 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001931
David Sodman99974d22017-11-28 12:04:33 -08001932 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001933 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1934 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001935 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001936}
1937
David Sodman2b406362017-12-15 13:33:47 -08001938void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001939{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 ATRACE_CALL();
1941 ALOGV("postComposition");
1942
Brian Anderson3546a3f2016-07-14 11:51:14 -07001943 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001944 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001945 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001946 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001947 }
1948
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001949 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001950 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001951
David Sodman73beded2017-11-15 11:56:06 -08001952 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001953 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001954 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001955 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001956 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001957 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001958 } else {
1959 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1960 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001961
David Sodman73beded2017-11-15 11:56:06 -08001962 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001963 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001964 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001965 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001966 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001967
Ana Krulece588e312018-09-18 12:32:24 -07001968 DisplayStatInfo stats;
1969 if (mUseScheduler) {
1970 mScheduler->getDisplayStatInfo(&stats);
1971 } else {
1972 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1973 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1974 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001975
David Sodman2b406362017-12-15 13:33:47 -08001976 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001977 // when we started doing work for this frame, but that should be okay
1978 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001979 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001980 CompositorTiming compositorTiming;
1981 {
David Sodman99974d22017-11-28 12:04:33 -08001982 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1983 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001984 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001985
Robert Carr2047fae2016-11-28 14:09:09 -08001986 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001987 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1988 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001989 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001990 recordBufferingStats(layer->getName().string(),
1991 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001992 }
Robert Carr2047fae2016-11-28 14:09:09 -08001993 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001994
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001995 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001996 if (mUseScheduler) {
1997 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001998 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001999 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2000 enableHardwareVsync();
2001 } else {
2002 disableHardwareVsync(false);
2003 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002004 }
2005 }
2006
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002007 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002008 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002009 if (mUseScheduler) {
2010 mScheduler->enableHardwareVsync();
2011 } else {
2012 enableHardwareVsync();
2013 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002014 }
2015 }
2016
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002017 if (mAnimCompositionPending) {
2018 mAnimCompositionPending = false;
2019
Brian Anderson4e606e32017-03-16 15:34:57 -07002020 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002021 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002022 std::move(presentFenceTime));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002023 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002024 // The HWC doesn't support present fences, so use the refresh
2025 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002026 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002027 mAnimFrameTracker.setActualPresentTime(presentTime);
2028 }
2029 mAnimFrameTracker.advanceFrame();
2030 }
Dan Stozab90cf072015-03-05 11:05:59 -08002031
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002032 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002033 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002034 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002035 }
2036
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002037 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002038
Dominik Laskowski075d3172018-05-24 15:50:06 -07002039 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002040 return;
2041 }
2042
2043 nsecs_t currentTime = systemTime();
2044 if (mHasPoweredOff) {
2045 mHasPoweredOff = false;
2046 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002047 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002048 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002049 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2050 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002051 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002052 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002053 }
David Sodman4a36e932017-11-07 14:29:47 -08002054 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002055 }
David Sodman4a36e932017-11-07 14:29:47 -08002056 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002057
2058 {
2059 std::lock_guard lock(mTexturePoolMutex);
2060 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
2061 if (refillCount > 0) {
2062 const size_t offset = mTexturePool.size();
2063 mTexturePool.resize(mTexturePoolSize);
2064 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2065 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2066 }
2067 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002068
Marissa Wallfda30bb2018-10-12 11:34:28 -07002069 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002070 mTransactionCompletedThread.sendCallbacks();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002071}
2072
2073void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002074 ATRACE_CALL();
2075 ALOGV("rebuildLayerStacks");
2076
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002077 // We need to clear these out now as these may be holding on to a
2078 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2079 // also holds a reference. When the set of visible layers is recomputed,
2080 // some layers may be destroyed if the only thing keeping them alive was
2081 // that list of visible layers associated with each display. The layer
2082 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2083 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2084 for (const auto& [token, display] : mDisplays) {
2085 getBE().mCompositionInfo[token].clear();
2086 }
2087
Mathias Agopiancd60f992012-08-16 16:28:27 -07002088 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002089 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002090 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002091 mVisibleRegionsDirty = false;
2092 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002093
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002094 for (const auto& pair : mDisplays) {
2095 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002096 Region opaqueRegion;
2097 Region dirtyRegion;
2098 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002099 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002100 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002101 const Rect bounds = display->getBounds();
2102 if (display->isPoweredOn()) {
2103 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002104
Jeff Sharkey76488112017-02-27 14:15:18 -07002105 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002106 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002107 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002108 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002109 Region drawRegion(tr.transform(
2110 layer->visibleNonTransparentRegion));
2111 drawRegion.andSelf(bounds);
2112 if (!drawRegion.isEmpty()) {
2113 layersSortedByZ.add(layer);
2114 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002115 // Clear out the HWC layer if this layer was
2116 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002117 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002118 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002119 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002120 // WM changes display->layerStack upon sleep/awake.
2121 // Here we make sure we delete the HWC layers even if
2122 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002123 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002124 }
2125
2126 // If a layer is not going to get a release fence because
2127 // it is invisible, but it is also going to release its
2128 // old buffer, add it to the list of layers needing
2129 // fences.
2130 if (hwcLayerDestroyed) {
2131 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2132 mLayersWithQueuedFrames.cend(), layer);
2133 if (found != mLayersWithQueuedFrames.cend()) {
2134 layersNeedingFences.add(layer);
2135 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002136 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002137 });
2138 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002139 display->setVisibleLayersSortedByZ(layersSortedByZ);
2140 display->setLayersNeedingFences(layersNeedingFences);
2141 display->undefinedRegion.set(bounds);
2142 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2143 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002144 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002145 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002146}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002147
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002148// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002149// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002150// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002151// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002152// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002153// The returned HDR data space is one of
2154// - Dataspace::UNKNOWN
2155// - Dataspace::BT2020_HLG
2156// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002157Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2158 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002159 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002160 *outHdrDataSpace = Dataspace::UNKNOWN;
2161
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002162 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002163 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002164 case Dataspace::V0_SCRGB:
2165 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002166 case Dataspace::BT2020:
2167 case Dataspace::BT2020_ITU:
2168 case Dataspace::BT2020_LINEAR:
2169 case Dataspace::DISPLAY_BT2020:
2170 bestDataSpace = Dataspace::DISPLAY_BT2020;
2171 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002172 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002173 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002174 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002175 case Dataspace::BT2020_PQ:
2176 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002177 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002178 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002179 case Dataspace::BT2020_HLG:
2180 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002181 // When there's mixed PQ content and HLG content, we set the HDR
2182 // data space to be BT2020_PQ and convert HLG to PQ.
2183 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2184 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002185 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002186 break;
2187 default:
2188 break;
2189 }
Romain Guy54f154a2017-10-24 21:40:32 +01002190 }
2191
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002192 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002193}
2194
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002195// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002196void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2197 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002198 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2199 *outMode = ColorMode::NATIVE;
2200 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002201 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002202 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002203 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002204
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002205 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002206 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002207
Peiyong Lindfde5112018-06-05 10:58:41 -07002208 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002209 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002210 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002211 if (isHdr) {
2212 bestDataSpace = hdrDataSpace;
2213 }
2214
Chia-I Wu0d711262018-05-21 15:19:35 -07002215 RenderIntent intent;
2216 switch (mDisplayColorSetting) {
2217 case DisplayColorSetting::MANAGED:
2218 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002219 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002220 break;
2221 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002222 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002223 break;
2224 default: // vendor display color setting
2225 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2226 break;
2227 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002228
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002229 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002230}
2231
David Sodmanfa9b2af2017-12-24 13:28:59 -08002232void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002233{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002234 bool dirty = !display->getDirtyRegion(false).isEmpty();
2235 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2236 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002237
David Sodmanfa9b2af2017-12-24 13:28:59 -08002238 // If nothing has changed (!dirty), don't recompose.
2239 // If something changed, but we don't currently have any visible layers,
2240 // and didn't when we last did a composition, then skip it this time.
2241 // The second rule does two things:
2242 // - When all layers are removed from a display, we'll emit one black
2243 // frame, then nothing more until we get new layers.
2244 // - When a display is created with a private layer stack, we won't
2245 // emit any black frames until a layer is added to the layer stack.
2246 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002247
Dominik Laskowski075d3172018-05-24 15:50:06 -07002248 const char flagPrefix[] = {'-', '+'};
2249 static_cast<void>(flagPrefix);
2250 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2251 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2252 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002253
David Sodmanfa9b2af2017-12-24 13:28:59 -08002254 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002255
David Sodmanfa9b2af2017-12-24 13:28:59 -08002256 if (mustRecompose) {
2257 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002258 }
2259}
2260
David Sodmanfa9b2af2017-12-24 13:28:59 -08002261void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002262{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002263 if (!display->isPoweredOn()) {
2264 return;
David Sodman2b406362017-12-15 13:33:47 -08002265 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002266
Dominik Laskowski05275f12018-11-01 15:03:24 -07002267 status_t result = display->prepareFrame(getHwComposer(),
2268 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002269 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2270 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002271}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002272
David Sodmanfa9b2af2017-12-24 13:28:59 -08002273void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002274 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002275 ALOGV("doComposition");
2276
David Sodmanfa9b2af2017-12-24 13:28:59 -08002277 if (display->isPoweredOn()) {
2278 // transform the dirty region into this screen's coordinate space
2279 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002280
David Sodmanfa9b2af2017-12-24 13:28:59 -08002281 // repaint the framebuffer (if needed)
2282 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002283
David Sodmanfa9b2af2017-12-24 13:28:59 -08002284 display->dirtyRegion.clear();
2285 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002286 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002287 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002288}
2289
David Sodmanfa9b2af2017-12-24 13:28:59 -08002290void SurfaceFlinger::postFrame()
2291{
2292 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002293 const auto display = getDefaultDisplayDeviceLocked();
2294 if (display && getHwComposer().isConnected(*display->getId())) {
2295 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002296 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2297 logFrameStats();
2298 }
2299 }
2300}
2301
2302void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002303{
Mathias Agopian841cde52012-03-01 15:44:37 -08002304 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002305 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002306
David Sodmanfa9b2af2017-12-24 13:28:59 -08002307 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002308
David Sodmanfa9b2af2017-12-24 13:28:59 -08002309 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002310 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002311 if (displayId) {
2312 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002313 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002314 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002315 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002316 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002317
Chia-I Wu7b549592017-11-15 09:14:57 -08002318 // The layer buffer from the previous frame (if any) is released
2319 // by HWC only when the release fence from this frame (if any) is
2320 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002321 if (displayId && layer->hasHwcLayer(*displayId)) {
2322 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2323 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002324 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002325
2326 // If the layer was client composited in the previous frame, we
2327 // need to merge with the previous client target acquire fence.
2328 // Since we do not track that, always merge with the current
2329 // client target acquire fence when it is available, even though
2330 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002331 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002332 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002333 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002334 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002335
David Sodman15094112018-10-11 09:39:37 -07002336 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002337 }
Chia-I Wu83806892017-11-16 10:50:20 -08002338
2339 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002340 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002341 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002342 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002343 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002344 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002345 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002346 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002347 }
2348 }
2349
Dominik Laskowski075d3172018-05-24 15:50:06 -07002350 if (displayId) {
2351 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002352 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002354}
2355
Mathias Agopian87baae12012-07-31 12:38:26 -07002356void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002357{
Mathias Agopian841cde52012-03-01 15:44:37 -08002358 ATRACE_CALL();
2359
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002360 // here we keep a copy of the drawing state (that is the state that's
2361 // going to be overwritten by handleTransactionLocked()) outside of
2362 // mStateLock so that the side-effects of the State assignment
2363 // don't happen with mStateLock held (which can cause deadlocks).
2364 State drawingState(mDrawingState);
2365
Mathias Agopianca4d3602011-05-19 15:38:14 -07002366 Mutex::Autolock _l(mStateLock);
2367 const nsecs_t now = systemTime();
2368 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369
Mathias Agopianca4d3602011-05-19 15:38:14 -07002370 // Here we're guaranteed that some transaction flags are set
2371 // so we can call handleTransactionLocked() unconditionally.
2372 // We call getTransactionFlags(), which will also clear the flags,
2373 // with mStateLock held to guarantee that mCurrentState won't change
2374 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002375
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002376 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002377 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002378 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002379
Mathias Agopianca4d3602011-05-19 15:38:14 -07002380 mLastTransactionTime = systemTime() - now;
2381 mDebugInTransaction = 0;
2382 invalidateHwcGeometry();
2383 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002384}
2385
Lloyd Piqueba04e622017-12-14 17:11:26 -08002386void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2387 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002388 const std::optional<DisplayIdentificationInfo> info =
2389 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002390
Dominik Laskowski075d3172018-05-24 15:50:06 -07002391 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002392 continue;
2393 }
2394
Lloyd Piqueba04e622017-12-14 17:11:26 -08002395 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002396 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002397 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002398 mPhysicalDisplayTokens[info->id] = new BBinder();
2399 DisplayDeviceState state;
2400 state.displayId = info->id;
2401 state.isSecure = true; // All physical displays are currently considered secure.
2402 state.displayName = info->name;
2403 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2404 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002405 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002406 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002407 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002408
Dominik Laskowski075d3172018-05-24 15:50:06 -07002409 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2410 if (index >= 0) {
2411 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2412 mInterceptor->saveDisplayDeletion(state.sequenceId);
2413 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002414 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002415 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002416 }
2417
2418 processDisplayChangesLocked();
2419 }
2420
2421 mPendingHotplugEvents.clear();
2422}
2423
Lloyd Pique99d3da52018-01-22 17:48:03 -08002424sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002425 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2426 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2427 const sp<IGraphicBufferProducer>& producer) {
2428 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002429 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002430 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002431 creationArgs.isSecure = state.isSecure;
2432 creationArgs.displaySurface = dispSurface;
2433 creationArgs.hasWideColorGamut = false;
2434 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002435
Dominik Laskowski075d3172018-05-24 15:50:06 -07002436 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2437 creationArgs.isPrimary = isInternalDisplay;
2438
2439 if (useColorManagement && displayId) {
2440 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002441 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002442 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002443 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002444 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002445
Dominik Laskowski7e045462018-05-30 13:02:02 -07002446 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002447 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002448 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002449 }
tangrobin6753a022018-08-10 10:58:54 +08002450 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002451
Dominik Laskowski075d3172018-05-24 15:50:06 -07002452 if (displayId) {
2453 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002454 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002455 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002456 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002457
Lloyd Pique90c115d2018-09-18 21:39:42 -07002458 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002459 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002460 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002461
Lloyd Pique99d3da52018-01-22 17:48:03 -08002462 // Make sure that composition can never be stalled by a virtual display
2463 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002464 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002465 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002466 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2467 }
2468
Dominik Laskowski075d3172018-05-24 15:50:06 -07002469 creationArgs.displayInstallOrientation =
2470 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002471
Lloyd Pique99d3da52018-01-22 17:48:03 -08002472 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002473 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002474
Lloyd Pique90c115d2018-09-18 21:39:42 -07002475 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002476
2477 if (maxFrameBufferAcquiredBuffers >= 3) {
2478 nativeWindowSurface->preallocateBuffers();
2479 }
2480
2481 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002482 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002483 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002484 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002485 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002486 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002487 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002488 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002489 if (!state.isVirtual()) {
2490 LOG_ALWAYS_FATAL_IF(!displayId);
2491 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002492 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002493
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002494 display->setLayerStack(state.layerStack);
2495 display->setProjection(state.orientation, state.viewport, state.frame);
2496 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002497
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002498 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002499}
2500
Lloyd Pique347200f2017-12-14 17:00:15 -08002501void SurfaceFlinger::processDisplayChangesLocked() {
2502 // here we take advantage of Vector's copy-on-write semantics to
2503 // improve performance by skipping the transaction entirely when
2504 // know that the lists are identical
2505 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2506 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2507 if (!curr.isIdenticalTo(draw)) {
2508 mVisibleRegionsDirty = true;
2509 const size_t cc = curr.size();
2510 size_t dc = draw.size();
2511
2512 // find the displays that were removed
2513 // (ie: in drawing state but not in current state)
2514 // also handle displays that changed
2515 // (ie: displays that are in both lists)
2516 for (size_t i = 0; i < dc;) {
2517 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2518 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002519 // Save display IDs before disconnecting.
2520 const auto internalDisplayId = getInternalDisplayId();
2521 const auto externalDisplayId = getExternalDisplayId();
2522
Lloyd Pique347200f2017-12-14 17:00:15 -08002523 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002524 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2525 display->disconnect(getHwComposer());
2526 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002527 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002528 if (mUseScheduler) {
2529 mScheduler->hotplugReceived(mAppConnectionHandle,
2530 EventThread::DisplayType::Primary, false);
2531 } else {
2532 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2533 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002535 if (mUseScheduler) {
2536 mScheduler->hotplugReceived(mAppConnectionHandle,
2537 EventThread::DisplayType::External, false);
2538 } else {
2539 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2540 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002541 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002542 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002543 } else {
2544 // this display is in both lists. see if something changed.
2545 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002546 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002547 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2548 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2549 if (state_binder != draw_binder) {
2550 // changing the surface is like destroying and
2551 // recreating the DisplayDevice, so we just remove it
2552 // from the drawing state, so that it get re-added
2553 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002554 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2555 display->disconnect(getHwComposer());
2556 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002557 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002558 mDrawingState.displays.removeItemsAt(i);
2559 dc--;
2560 // at this point we must loop to the next item
2561 continue;
2562 }
2563
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002564 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002565 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002566 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002567 }
2568 if ((state.orientation != draw[i].orientation) ||
2569 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002570 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002571 }
2572 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002573 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002574 }
2575 }
2576 }
2577 ++i;
2578 }
2579
2580 // find displays that were added
2581 // (ie: in current state but not in drawing state)
2582 for (size_t i = 0; i < cc; i++) {
2583 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2584 const DisplayDeviceState& state(curr[i]);
2585
2586 sp<DisplaySurface> dispSurface;
2587 sp<IGraphicBufferProducer> producer;
2588 sp<IGraphicBufferProducer> bqProducer;
2589 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002590 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002591
Dominik Laskowski075d3172018-05-24 15:50:06 -07002592 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002593 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002594 // Virtual displays without a surface are dormant:
2595 // they have external state (layer stack, projection,
2596 // etc.) but no internal state (i.e. a DisplayDevice).
2597 if (state.surface != nullptr) {
2598 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002599 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002600 int width = 0;
2601 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2602 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2603 int height = 0;
2604 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2605 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2606 int intFormat = 0;
2607 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2608 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002609 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002610
Dominik Laskowski075d3172018-05-24 15:50:06 -07002611 displayId =
2612 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002613 }
2614
2615 // TODO: Plumb requested format back up to consumer
2616
2617 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002618 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002619 bqProducer, bqConsumer,
2620 state.displayName);
2621
2622 dispSurface = vds;
2623 producer = vds;
2624 }
2625 } else {
2626 ALOGE_IF(state.surface != nullptr,
2627 "adding a supported display, but rendering "
2628 "surface is provided (%p), ignoring it",
2629 state.surface.get());
2630
Dominik Laskowski075d3172018-05-24 15:50:06 -07002631 displayId = state.displayId;
2632 LOG_ALWAYS_FATAL_IF(!displayId);
2633 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002634 producer = bqProducer;
2635 }
2636
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002637 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002638 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002639 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002640 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002641 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002642 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002643 LOG_ALWAYS_FATAL_IF(!displayId);
2644
2645 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002646 if (mUseScheduler) {
2647 mScheduler->hotplugReceived(mAppConnectionHandle,
2648 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002649 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002650 } else {
2651 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2652 true);
2653 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002654 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002655 if (mUseScheduler) {
2656 mScheduler->hotplugReceived(mAppConnectionHandle,
2657 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002658 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002659 } else {
2660 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2661 true);
2662 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002663 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002664 }
2665 }
2666 }
2667 }
2668 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002669
2670 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002671}
2672
Mathias Agopian87baae12012-07-31 12:38:26 -07002673void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002674{
Dan Stoza7dde5992015-05-22 09:51:44 -07002675 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002676 mCurrentState.traverseInZOrder([](Layer* layer) {
2677 layer->notifyAvailableFrames();
2678 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002679
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680 /*
2681 * Traversal of the children
2682 * (perform the transaction for each of them if needed)
2683 */
2684
Robert Carr720e5062018-07-30 17:45:14 -07002685 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002686 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002687 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002688 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002689 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690
2691 const uint32_t flags = layer->doTransaction(0);
2692 if (flags & Layer::eVisibleRegion)
2693 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002694
2695 if (flags & Layer::eInputInfoChanged) {
2696 inputChanged = true;
2697 }
Robert Carr2047fae2016-11-28 14:09:09 -08002698 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 }
2700
2701 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002702 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002703 */
2704
Mathias Agopiane57f2922012-08-09 16:29:12 -07002705 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002706 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002707 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002708 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002710 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002711 // The transform hint might have changed for some layers
2712 // (either because a display has changed, or because a layer
2713 // as changed).
2714 //
2715 // Walk through all the layers in currentLayers,
2716 // and update their transform hint.
2717 //
2718 // If a layer is visible only on a single display, then that
2719 // display is used to calculate the hint, otherwise we use the
2720 // default display.
2721 //
2722 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2723 // the hint is set before we acquire a buffer from the surface texture.
2724 //
2725 // NOTE: layer transactions have taken place already, so we use their
2726 // drawing state. However, SurfaceFlinger's own transaction has not
2727 // happened yet, so we must use the current state layer list
2728 // (soon to become the drawing state list).
2729 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002730 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002731 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002732 bool first = true;
2733 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002734 // NOTE: we rely on the fact that layers are sorted by
2735 // layerStack first (so we don't have to traverse the list
2736 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002737 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002738 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002739 currentlayerStack = layerStack;
2740 // figure out if this layerstack is mirrored
2741 // (more than one display) if so, pick the default display,
2742 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002743 hintDisplay = nullptr;
2744 for (const auto& [token, display] : mDisplays) {
2745 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2746 if (hintDisplay) {
2747 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002748 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002749 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002750 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002751 }
2752 }
2753 }
2754 }
Chet Haase91d25932013-04-11 15:24:55 -07002755
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002756 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002757 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2758 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002759
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002760 // could be null when this layer is using a layerStack
2761 // that is not visible on any display. Also can occur at
2762 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002763 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002764 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002765
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002766 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002767 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002768 if (hintDisplay) {
2769 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002770 }
Robert Carr2047fae2016-11-28 14:09:09 -08002771
2772 first = false;
2773 });
Mathias Agopian84300952012-11-21 16:02:13 -08002774 }
2775
2776
Mathias Agopian3559b072012-08-15 13:46:03 -07002777 /*
2778 * Perform our own transaction if needed
2779 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002780
2781 if (mLayersAdded) {
2782 mLayersAdded = false;
2783 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002784 mVisibleRegionsDirty = true;
2785 }
2786
2787 // some layers might have been removed, so
2788 // we need to update the regions they're exposing.
2789 if (mLayersRemoved) {
2790 mLayersRemoved = false;
2791 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002792 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002793 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002794 // this layer is not visible anymore
2795 // TODO: we could traverse the tree from front to back and
2796 // compute the actual visible region
2797 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002798 Region visibleReg;
2799 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002800 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002801 }
Robert Carr2047fae2016-11-28 14:09:09 -08002802 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803 }
2804
2805 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002806
Vishnu Nairde19f852018-12-18 16:11:53 -08002807 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002808 updateInputWindows();
2809 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002810 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002811
Riley Andrews03414a12014-07-01 14:22:59 -07002812 updateCursorAsync();
2813}
2814
Robert Carr720e5062018-07-30 17:45:14 -07002815void SurfaceFlinger::updateInputWindows() {
2816 ATRACE_CALL();
2817
Vishnu Nairde19f852018-12-18 16:11:53 -08002818 if (mInputFlinger == nullptr) {
2819 return;
2820 }
2821
Robert Carr720e5062018-07-30 17:45:14 -07002822 Vector<InputWindowInfo> inputHandles;
2823
2824 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2825 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002826 // When calculating the screen bounds we ignore the transparent region since it may
2827 // result in an unwanted offset.
2828 inputHandles.add(layer->fillInputInfo(
2829 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002830 }
2831 });
2832 mInputFlinger->setInputWindows(inputHandles);
2833}
2834
chaviwfbe5d9c2018-12-26 12:23:37 -08002835void SurfaceFlinger::executeInputWindowCommands() {
2836 if (!mInputFlinger) {
2837 return;
2838 }
2839
2840 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2841 if (transferTouchFocusCommand.fromToken != nullptr &&
2842 transferTouchFocusCommand.toToken != nullptr &&
2843 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2844 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2845 transferTouchFocusCommand.toToken);
2846 }
2847 }
2848
2849 mInputWindowCommands.clear();
2850}
2851
Riley Andrews03414a12014-07-01 14:22:59 -07002852void SurfaceFlinger::updateCursorAsync()
2853{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002854 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002855 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002856 continue;
2857 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002858
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002859 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2860 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002861 }
2862 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002863}
2864
chaviw61626f22018-11-15 16:26:27 -08002865void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2866 if (layer->hasReadyFrame()) {
2867 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2868 if (layer->shouldPresentNow(expectedPresentTime)) {
2869 bool ignored = false;
2870 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2871 }
2872 }
2873 layer->releasePendingBuffer(systemTime());
2874}
2875
Mathias Agopian4fec8732012-06-29 14:12:52 -07002876void SurfaceFlinger::commitTransaction()
2877{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002878 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002879 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002880 for (const auto& l : mLayersPendingRemoval) {
2881 recordBufferingStats(l->getName().string(),
2882 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002883
2884 // We need to release the HWC layers when the Layer is removed
2885 // from the current state otherwise the HWC layer just continues
2886 // showing at its last configured state until we eventually
2887 // abandon the buffer queue.
2888 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002889 l->destroyHwcLayersForAllDisplays();
2890 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002891 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002892 }
2893 mLayersPendingRemoval.clear();
2894 }
2895
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002896 // If this transaction is part of a window animation then the next frame
2897 // we composite should be considered an animation as well.
2898 mAnimCompositionPending = mAnimTransactionPending;
2899
Mathias Agopian4fec8732012-06-29 14:12:52 -07002900 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002901 // clear the "changed" flags in current state
2902 mCurrentState.colorMatrixChanged = false;
2903
Robert Carr1f0a16a2016-10-24 16:27:39 -07002904 mDrawingState.traverseInZOrder([](Layer* layer) {
2905 layer->commitChildList();
2906 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002907 mTransactionPending = false;
2908 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002909 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910}
2911
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002912void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2913 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002914 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002915 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002916
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002917 Region aboveOpaqueLayers;
2918 Region aboveCoveredLayers;
2919 Region dirty;
2920
Mathias Agopian87baae12012-07-31 12:38:26 -07002921 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922
Robert Carr2047fae2016-11-28 14:09:09 -08002923 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002924 // start with the whole surface at its current location
2925 const Layer::State& s(layer->getDrawingState());
2926
Jesse Hall01e29052013-02-19 16:13:35 -08002927 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002928 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002929 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002930 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002931
Mathias Agopianab028732010-03-16 16:41:46 -07002932 /*
2933 * opaqueRegion: area of a surface that is fully opaque.
2934 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002936
2937 /*
2938 * visibleRegion: area of a surface that is visible on screen
2939 * and not fully transparent. This is essentially the layer's
2940 * footprint minus the opaque regions above it.
2941 * Areas covered by a translucent surface are considered visible.
2942 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002944
2945 /*
2946 * coveredRegion: area of a surface that is covered by all
2947 * visible regions above it (which includes the translucent areas).
2948 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002949 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002950
Jesse Halla8026d22012-09-25 13:25:04 -07002951 /*
2952 * transparentRegion: area of a surface that is hinted to be completely
2953 * transparent. This is only used to tell when the layer has no visible
2954 * non-transparent regions and can be removed from the layer list. It
2955 * does not affect the visibleRegion of this layer or any layers
2956 * beneath it. The hint may not be correct if apps don't respect the
2957 * SurfaceView restrictions (which, sadly, some don't).
2958 */
2959 Region transparentRegion;
2960
Mathias Agopianab028732010-03-16 16:41:46 -07002961
2962 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002963 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002964 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002965 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07002966
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002967 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002968 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002969 if (!visibleRegion.isEmpty()) {
2970 // Remove the transparent area from the visible region
2971 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002972 if (tr.preserveRects()) {
2973 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002974 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002975 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002976 // transformation too complex, can't do the
2977 // transparent region optimization.
2978 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002979 }
Mathias Agopianab028732010-03-16 16:41:46 -07002980 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002981
Mathias Agopianab028732010-03-16 16:41:46 -07002982 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002983 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002984 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002985 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002986 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002987 // the opaque region is the layer's footprint
2988 opaqueRegion = visibleRegion;
2989 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002990 }
2991 }
2992
Robert Carre5f4f692018-01-12 13:12:28 -08002993 if (visibleRegion.isEmpty()) {
2994 layer->clearVisibilityRegions();
2995 return;
2996 }
2997
Mathias Agopianab028732010-03-16 16:41:46 -07002998 // Clip the covered region to the visible region
2999 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3000
3001 // Update aboveCoveredLayers for next (lower) layer
3002 aboveCoveredLayers.orSelf(visibleRegion);
3003
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003004 // subtract the opaque region covered by the layers above us
3005 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003006
3007 // compute this layer's dirty region
3008 if (layer->contentDirty) {
3009 // we need to invalidate the whole region
3010 dirty = visibleRegion;
3011 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003012 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003013 layer->contentDirty = false;
3014 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003015 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003016 * the exposed region consists of two components:
3017 * 1) what's VISIBLE now and was COVERED before
3018 * 2) what's EXPOSED now less what was EXPOSED before
3019 *
3020 * note that (1) is conservative, we start with the whole
3021 * visible region but only keep what used to be covered by
3022 * something -- which mean it may have been exposed.
3023 *
3024 * (2) handles areas that were not covered by anything but got
3025 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003026 */
Mathias Agopianab028732010-03-16 16:41:46 -07003027 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003028 const Region oldVisibleRegion = layer->visibleRegion;
3029 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003030 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3031 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003032 }
3033 dirty.subtractSelf(aboveOpaqueLayers);
3034
3035 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003036 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003037
Mathias Agopianab028732010-03-16 16:41:46 -07003038 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003040
Jesse Halla8026d22012-09-25 13:25:04 -07003041 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003042 layer->setVisibleRegion(visibleRegion);
3043 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003044 layer->setVisibleNonTransparentRegion(
3045 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003046 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003047
Mathias Agopian87baae12012-07-31 12:38:26 -07003048 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049}
3050
Chia-I Wuab0c3192017-08-01 11:29:00 -07003051void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003052 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003053 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3054 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003055 }
3056 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003057}
3058
Dan Stoza6b9454d2014-11-07 16:00:59 -08003059bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003060{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003061 ALOGV("handlePageFlip");
3062
Brian Andersond6927fb2016-07-23 23:37:30 -07003063 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064
Mathias Agopian4fec8732012-06-29 14:12:52 -07003065 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003066 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003067 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003068
3069 // Store the set of layers that need updates. This set must not change as
3070 // buffers are being latched, as this could result in a deadlock.
3071 // Example: Two producers share the same command stream and:
3072 // 1.) Layer 0 is latched
3073 // 2.) Layer 0 gets a new frame
3074 // 2.) Layer 1 gets a new frame
3075 // 3.) Layer 1 is latched.
3076 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3077 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003078 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003079 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003080 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003081 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3082 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003083 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003084 } else {
3085 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003086 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003087 } else {
3088 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003089 }
Robert Carr2047fae2016-11-28 14:09:09 -08003090 });
3091
Lloyd Piquef2c79392018-12-20 16:23:33 -08003092 if (!mLayersWithQueuedFrames.empty()) {
3093 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3094 // writes to Layer current state. See also b/119481871
3095 Mutex::Autolock lock(mStateLock);
3096
3097 for (auto& layer : mLayersWithQueuedFrames) {
3098 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3099 layer->useSurfaceDamage();
3100 invalidateLayerStack(layer, dirty);
3101 if (layer->isBufferLatched()) {
3102 newDataLatched = true;
3103 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003104 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003105 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003106
Alec Mouri86770e52018-09-24 22:40:58 +00003107 // Clear the renderengine fence here...
3108 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3109 // clear instead of sp::clear.
3110 getBE().flushFence = Fence::NO_FENCE;
3111
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003112 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003113
Vishnu Nairde19f852018-12-18 16:11:53 -08003114 if (visibleRegions) {
3115 // Update input window info if the layer receives its first buffer.
3116 updateInputWindows();
3117 }
3118
Dan Stoza6b9454d2014-11-07 16:00:59 -08003119 // If we will need to wake up at some time in the future to deal with a
3120 // queued frame that shouldn't be displayed during this vsync period, wake
3121 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003122 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003123 signalLayerUpdate();
3124 }
3125
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003126 // enter boot animation on first buffer latch
3127 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3128 ALOGI("Enter boot animation");
3129 mBootStage = BootStage::BOOTANIMATION;
3130 }
3131
Dan Stoza6b9454d2014-11-07 16:00:59 -08003132 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003133 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134}
3135
Mathias Agopianad456f92011-01-13 17:53:01 -08003136void SurfaceFlinger::invalidateHwcGeometry()
3137{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003138 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003139}
3140
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003141void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003142 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003143 // We only need to actually compose the display if:
3144 // 1) It is being handled by hardware composer, which may need this to
3145 // keep its virtual display state machine in sync, or
3146 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003147 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003148 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003149 return;
3150 }
3151
Dan Stoza9e56aa02015-11-02 13:00:03 -08003152 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003153 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003154
3155 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003156 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157}
3158
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003159bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003160 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003161
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003162 const Region bounds(display->bounds());
3163 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003164 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07003165 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003166 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003167
Peiyong Lind3788632018-09-18 16:01:31 -07003168 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003169 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003170
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003171 // Framebuffer will live in this scope for GPU composition.
3172 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3173
Dan Stoza9e56aa02015-11-02 13:00:03 -08003174 if (hasClientComposition) {
3175 ALOGV("hasClientComposition");
3176
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003177 sp<GraphicBuffer> buf = display->dequeueBuffer();
3178
3179 if (buf == nullptr) {
3180 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3181 "client composition for this frame",
3182 display->getDisplayName().c_str());
3183 return false;
3184 }
3185
3186 // Bind the framebuffer in this scope.
3187 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3188 buf->getNativeBuffer());
3189
3190 if (fbo->getStatus() != NO_ERROR) {
3191 ALOGW("Binding buffer for display [%s] failed with status: %d",
3192 display->getDisplayName().c_str(), fbo->getStatus());
3193 return false;
3194 }
3195
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003196 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003197 if (display->hasWideColorGamut()) {
3198 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003199 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003200 getRenderEngine().setOutputDataSpace(outputDataspace);
3201 getRenderEngine().setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003202 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003203
Lloyd Pique441d5042018-10-18 16:49:51 -07003204 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003205 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003206 getHwComposer()
3207 .hasDisplayCapability(displayId,
3208 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003209
Peiyong Lind3788632018-09-18 16:01:31 -07003210 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003211 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3212 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003213 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003214 }
3215
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003216 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003217
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003218 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003219 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003220 // when using overlays, we assume a fully transparent framebuffer
3221 // NOTE: we could reduce how much we need to clear, for instance
3222 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003223 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003224 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003225 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003226 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003227 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003228 // we're left with the letterbox region
3229 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003230 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003231
3232 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003233 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003234
Mathias Agopianb9494d52012-04-18 02:28:45 -07003235 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003236 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003237 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003238 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003239 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003240 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003241
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003242 const Rect& bounds = display->getBounds();
3243 const Rect& scissor = display->getScissor();
3244 if (scissor != bounds) {
3245 // scissor doesn't match the screen's dimensions, so we
3246 // need to clear everything outside of it and enable
3247 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003248
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003249 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003250 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003251 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003252 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003253
Mathias Agopian85d751c2012-08-29 16:59:24 -07003254 /*
3255 * and then, render the layers targeted at the framebuffer
3256 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003257
Dan Stoza9e56aa02015-11-02 13:00:03 -08003258 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003259 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003260 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003261 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003262 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003263 displayTransform.transform(layer->visibleRegion)));
3264 ALOGV("Layer: %s", layer->getName().string());
3265 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003266 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003267 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003268 case HWC2::Composition::Cursor:
3269 case HWC2::Composition::Device:
3270 case HWC2::Composition::Sideband:
3271 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003272 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003273 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003274 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003275 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003276 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003277 // never clear the very first layer since we're
3278 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003279 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003280 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003281 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003282 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003283 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003284 if (layer->hasColorTransform()) {
3285 mat4 tmpMatrix;
3286 if (applyColorMatrix) {
3287 tmpMatrix = mDrawingState.colorMatrix;
3288 }
3289 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003290 getRenderEngine().setColorTransform(tmpMatrix);
3291 } else {
3292 getRenderEngine().setColorTransform(colorMatrix);
3293 }
David Sodmanc1498e62018-09-12 14:36:26 -07003294 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003295 break;
3296 }
3297 default:
3298 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003299 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003300 } else {
3301 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003302 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003303 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003304 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003305
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003306 // Perform some cleanup steps if we used client composition.
3307 if (hasClientComposition) {
3308 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003309 getRenderEngine().disableScissor();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003310 display->finishBuffer();
3311 // Clear out error flags here so that we don't wait until next
3312 // composition to log.
3313 getRenderEngine().checkErrors();
3314 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003315 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003316}
3317
Chia-I Wu28e3a252018-09-07 12:05:02 -07003318void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003319 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003320 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003321}
3322
Dan Stoza7d89d062015-04-30 13:29:25 -07003323status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003324 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003325 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003326 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003327 const sp<Layer>& parent,
3328 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003329{
Dan Stoza7d89d062015-04-30 13:29:25 -07003330 // add this layer to the current state list
3331 {
3332 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003333 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003334 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3335 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003336 return NO_MEMORY;
3337 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003338 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003339 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003340 } else if (parent == nullptr) {
3341 lbc->onRemovedFromCurrentState();
3342 } else if (parent->isRemovedFromCurrentState()) {
3343 parent->addChild(lbc);
3344 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003345 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003346 parent->addChild(lbc);
3347 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003348
Yiwei Zhang243b3782018-05-15 17:40:04 -07003349 if (gbc != nullptr) {
3350 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3351 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3352 mMaxGraphicBufferProducerListSize,
3353 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3354 mGraphicBufferProducerList.size(),
3355 mMaxGraphicBufferProducerListSize, mNumLayers);
3356 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003357 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003358 }
3359
Mathias Agopian96f08192010-06-02 23:28:45 -07003360 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003361 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003362
Dan Stoza7d89d062015-04-30 13:29:25 -07003363 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003364}
3365
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003366uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003367 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003368}
3369
Mathias Agopian3f844832013-08-07 21:24:32 -07003370uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003371 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003372}
3373
Mathias Agopian3f844832013-08-07 21:24:32 -07003374uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003375 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003376}
3377
3378uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003379 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003380 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003381 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003382 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003383 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003384 }
3385 return old;
3386}
3387
Marissa Wall713b63f2018-10-17 15:42:43 -07003388bool SurfaceFlinger::flushTransactionQueues() {
3389 Mutex::Autolock _l(mStateLock);
3390 auto it = mTransactionQueues.begin();
3391 while (it != mTransactionQueues.end()) {
3392 auto& [applyToken, transactionQueue] = *it;
3393
3394 while (!transactionQueue.empty()) {
3395 const auto& [states, displays, flags] = transactionQueue.front();
3396 if (composerStateContainsUnsignaledFences(states)) {
3397 break;
3398 }
chaviw273171b2018-12-26 11:46:30 -08003399 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003400 transactionQueue.pop();
3401 }
3402
3403 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3404 }
3405 return mTransactionQueues.empty();
3406}
3407
chaviwca27f252018-02-06 16:46:39 -08003408bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3409 for (const ComposerState& state : states) {
3410 // Here we need to check that the interface we're given is indeed
3411 // one of our own. A malicious client could give us a nullptr
3412 // IInterface, or one of its own or even one of our own but a
3413 // different type. All these situations would cause us to crash.
3414 if (state.client == nullptr) {
3415 return true;
3416 }
3417
3418 sp<IBinder> binder = IInterface::asBinder(state.client);
3419 if (binder == nullptr) {
3420 return true;
3421 }
3422
3423 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3424 return true;
3425 }
3426 }
3427 return false;
3428}
3429
Marissa Wall713b63f2018-10-17 15:42:43 -07003430bool SurfaceFlinger::composerStateContainsUnsignaledFences(const Vector<ComposerState>& states) {
3431 for (const ComposerState& state : states) {
3432 const layer_state_t& s = state.state;
3433 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3434 continue;
3435 }
3436 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
3437 return true;
3438 }
3439 }
3440 return false;
3441}
3442
3443void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3444 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003445 const sp<IBinder>& applyToken,
3446 const InputWindowCommands& inputWindowCommands) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003447 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003448 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003449
chaviwca27f252018-02-06 16:46:39 -08003450 if (containsAnyInvalidClientState(states)) {
3451 return;
3452 }
3453
Marissa Wall713b63f2018-10-17 15:42:43 -07003454 // If its TransactionQueue already has a pending TransactionState or if it is pending
3455 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
3456 composerStateContainsUnsignaledFences(states)) {
3457 mTransactionQueues[applyToken].emplace(states, displays, flags);
3458 setTransactionFlags(eTransactionNeeded);
3459 return;
3460 }
3461
chaviw273171b2018-12-26 11:46:30 -08003462 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003463}
3464
3465void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003466 const Vector<DisplayState>& displays, uint32_t flags,
3467 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003468 uint32_t transactionFlags = 0;
3469
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003470 if (flags & eAnimation) {
3471 // For window updates that are part of an animation we must wait for
3472 // previous animation "frames" to be handled.
3473 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003474 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003475 if (CC_UNLIKELY(err != NO_ERROR)) {
3476 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003477 // caller after a few seconds.
3478 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3479 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003480 mAnimTransactionPending = false;
3481 break;
3482 }
3483 }
3484 }
3485
chaviwca27f252018-02-06 16:46:39 -08003486 for (const DisplayState& display : displays) {
3487 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003488 }
3489
Marissa Walle2ffb422018-10-12 11:33:52 -07003490 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003491 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003492 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003493 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003494 // If the state doesn't require a traversal and there are callbacks, send them now
3495 if (!(clientStateFlags & eTraversalNeeded)) {
3496 mTransactionCompletedThread.sendCallbacks();
3497 }
3498 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003499
chaviw273171b2018-12-26 11:46:30 -08003500 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3501
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003502 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3503 // anyway. This can be used as a flush mechanism for previous async transactions.
3504 // Empty animation transaction can be used to simulate back-pressure, so also force a
3505 // transaction for empty animation transactions.
3506 if (transactionFlags == 0 &&
3507 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003508 transactionFlags = eTransactionNeeded;
3509 }
3510
Mathias Agopian386aa982011-11-07 21:58:03 -08003511 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003512 if (mInterceptor->isEnabled()) {
3513 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003514 }
Irvel468051e2016-06-13 16:44:44 -07003515
Mathias Agopian386aa982011-11-07 21:58:03 -08003516 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003517 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3518 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003519 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003520
3521 // if this is a synchronous transaction, wait for it to take effect
3522 // before returning.
3523 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003524 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003525 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003526 if (flags & eAnimation) {
3527 mAnimTransactionPending = true;
3528 }
3529 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003530 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3531 if (CC_UNLIKELY(err != NO_ERROR)) {
3532 // just in case something goes wrong in SF, return to the
3533 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003534 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3535 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003536 break;
3537 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003538 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003539 }
3540}
3541
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003542uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3543 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3544 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003545
Mathias Agopiane57f2922012-08-09 16:29:12 -07003546 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003547 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3548
3549 const uint32_t what = s.what;
3550 if (what & DisplayState::eSurfaceChanged) {
3551 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3552 state.surface = s.surface;
3553 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003554 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003555 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003556 if (what & DisplayState::eLayerStackChanged) {
3557 if (state.layerStack != s.layerStack) {
3558 state.layerStack = s.layerStack;
3559 flags |= eDisplayTransactionNeeded;
3560 }
3561 }
3562 if (what & DisplayState::eDisplayProjectionChanged) {
3563 if (state.orientation != s.orientation) {
3564 state.orientation = s.orientation;
3565 flags |= eDisplayTransactionNeeded;
3566 }
3567 if (state.frame != s.frame) {
3568 state.frame = s.frame;
3569 flags |= eDisplayTransactionNeeded;
3570 }
3571 if (state.viewport != s.viewport) {
3572 state.viewport = s.viewport;
3573 flags |= eDisplayTransactionNeeded;
3574 }
3575 }
3576 if (what & DisplayState::eDisplaySizeChanged) {
3577 if (state.width != s.width) {
3578 state.width = s.width;
3579 flags |= eDisplayTransactionNeeded;
3580 }
3581 if (state.height != s.height) {
3582 state.height = s.height;
3583 flags |= eDisplayTransactionNeeded;
3584 }
3585 }
3586
Mathias Agopiane57f2922012-08-09 16:29:12 -07003587 return flags;
3588}
3589
Robert Carrd4ae7f32018-06-07 16:10:57 -07003590bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3591 IPCThreadState* ipc = IPCThreadState::self();
3592 const int pid = ipc->getCallingPid();
3593 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003594 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003595 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003596 return false;
3597 }
3598 return true;
3599}
3600
chaviwca27f252018-02-06 16:46:39 -08003601uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3602 const layer_state_t& s = composerState.state;
3603 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3604
Mathias Agopian13127d82013-03-05 17:47:11 -08003605 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003606 if (layer == nullptr) {
3607 return 0;
3608 }
3609
chaviw8b3871a2017-11-01 17:41:01 -07003610 uint32_t flags = 0;
3611
Garfield Tan8a3083e2018-12-03 13:21:07 -08003612 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003613 bool geometryAppliesWithResize =
3614 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003615
3616 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3617 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003618 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003619 layer->pushPendingState();
3620 }
3621
chaviw8b3871a2017-11-01 17:41:01 -07003622 if (what & layer_state_t::ePositionChanged) {
3623 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3624 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003625 }
chaviw8b3871a2017-11-01 17:41:01 -07003626 }
3627 if (what & layer_state_t::eLayerChanged) {
3628 // NOTE: index needs to be calculated before we update the state
3629 const auto& p = layer->getParent();
3630 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003631 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003632 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003633 mCurrentState.layersSortedByZ.removeAt(idx);
3634 mCurrentState.layersSortedByZ.add(layer);
3635 // we need traversal (state changed)
3636 // AND transaction (list changed)
3637 flags |= eTransactionNeeded|eTraversalNeeded;
3638 }
chaviw8b3871a2017-11-01 17:41:01 -07003639 } else {
3640 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003641 flags |= eTransactionNeeded|eTraversalNeeded;
3642 }
3643 }
chaviw8b3871a2017-11-01 17:41:01 -07003644 }
3645 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003646 // NOTE: index needs to be calculated before we update the state
3647 const auto& p = layer->getParent();
3648 if (p == nullptr) {
3649 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3650 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3651 mCurrentState.layersSortedByZ.removeAt(idx);
3652 mCurrentState.layersSortedByZ.add(layer);
3653 // we need traversal (state changed)
3654 // AND transaction (list changed)
3655 flags |= eTransactionNeeded|eTraversalNeeded;
3656 }
3657 } else {
3658 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3659 flags |= eTransactionNeeded|eTraversalNeeded;
3660 }
chaviw8b3871a2017-11-01 17:41:01 -07003661 }
3662 }
3663 if (what & layer_state_t::eSizeChanged) {
3664 if (layer->setSize(s.w, s.h)) {
3665 flags |= eTraversalNeeded;
3666 }
3667 }
3668 if (what & layer_state_t::eAlphaChanged) {
3669 if (layer->setAlpha(s.alpha))
3670 flags |= eTraversalNeeded;
3671 }
3672 if (what & layer_state_t::eColorChanged) {
3673 if (layer->setColor(s.color))
3674 flags |= eTraversalNeeded;
3675 }
Peiyong Lind3788632018-09-18 16:01:31 -07003676 if (what & layer_state_t::eColorTransformChanged) {
3677 if (layer->setColorTransform(s.colorTransform)) {
3678 flags |= eTraversalNeeded;
3679 }
3680 }
chaviw8b3871a2017-11-01 17:41:01 -07003681 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003682 // TODO: b/109894387
3683 //
3684 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3685 // rotation. To see the problem observe that if we have a square parent, and a child
3686 // of the same size, then we rotate the child 45 degrees around it's center, the child
3687 // must now be cropped to a non rectangular 8 sided region.
3688 //
3689 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3690 // private API, and the WindowManager only uses rotation in one case, which is on a top
3691 // level layer in which cropping is not an issue.
3692 //
3693 // However given that abuse of rotation matrices could lead to surfaces extending outside
3694 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3695 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3696 // transformations.
3697 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003698 flags |= eTraversalNeeded;
3699 }
3700 if (what & layer_state_t::eTransparentRegionChanged) {
3701 if (layer->setTransparentRegionHint(s.transparentRegion))
3702 flags |= eTraversalNeeded;
3703 }
3704 if (what & layer_state_t::eFlagsChanged) {
3705 if (layer->setFlags(s.flags, s.mask))
3706 flags |= eTraversalNeeded;
3707 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003708 if (what & layer_state_t::eCropChanged_legacy) {
3709 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003710 flags |= eTraversalNeeded;
3711 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003712 if (what & layer_state_t::eCornerRadiusChanged) {
3713 if (layer->setCornerRadius(s.cornerRadius))
3714 flags |= eTraversalNeeded;
3715 }
chaviw8b3871a2017-11-01 17:41:01 -07003716 if (what & layer_state_t::eLayerStackChanged) {
3717 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3718 // We only allow setting layer stacks for top level layers,
3719 // everything else inherits layer stack from its parent.
3720 if (layer->hasParent()) {
3721 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3722 layer->getName().string());
3723 } else if (idx < 0) {
3724 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3725 "that also does not appear in the top level layer list. Something"
3726 " has gone wrong.", layer->getName().string());
3727 } else if (layer->setLayerStack(s.layerStack)) {
3728 mCurrentState.layersSortedByZ.removeAt(idx);
3729 mCurrentState.layersSortedByZ.add(layer);
3730 // we need traversal (state changed)
3731 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003732 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003733 }
3734 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003735 if (what & layer_state_t::eDeferTransaction_legacy) {
3736 if (s.barrierHandle_legacy != nullptr) {
3737 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3738 } else if (s.barrierGbp_legacy != nullptr) {
3739 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003740 if (authenticateSurfaceTextureLocked(gbp)) {
3741 const auto& otherLayer =
3742 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003743 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003744 } else {
3745 ALOGE("Attempt to defer transaction to to an"
3746 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003747 }
3748 }
chaviw8b3871a2017-11-01 17:41:01 -07003749 // We don't trigger a traversal here because if no other state is
3750 // changed, we don't want this to cause any more work
3751 }
3752 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003753 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003754 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003755 if (!hadParent) {
3756 mCurrentState.layersSortedByZ.remove(layer);
3757 }
chaviw8b3871a2017-11-01 17:41:01 -07003758 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003759 }
chaviw8b3871a2017-11-01 17:41:01 -07003760 }
3761 if (what & layer_state_t::eReparentChildren) {
3762 if (layer->reparentChildren(s.reparentHandle)) {
3763 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003764 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003765 }
chaviw8b3871a2017-11-01 17:41:01 -07003766 if (what & layer_state_t::eDetachChildren) {
3767 layer->detachChildren();
3768 }
3769 if (what & layer_state_t::eOverrideScalingModeChanged) {
3770 layer->setOverrideScalingMode(s.overrideScalingMode);
3771 // We don't trigger a traversal here because if no other state is
3772 // changed, we don't want this to cause any more work
3773 }
Marissa Wall61c58622018-07-18 10:12:20 -07003774 if (what & layer_state_t::eTransformChanged) {
3775 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3776 }
3777 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3778 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3779 flags |= eTraversalNeeded;
3780 }
3781 if (what & layer_state_t::eCropChanged) {
3782 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3783 }
Marissa Wall861616d2018-10-22 12:52:23 -07003784 if (what & layer_state_t::eFrameChanged) {
3785 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3786 }
Marissa Wall61c58622018-07-18 10:12:20 -07003787 if (what & layer_state_t::eBufferChanged) {
3788 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3789 }
3790 if (what & layer_state_t::eAcquireFenceChanged) {
3791 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3792 }
3793 if (what & layer_state_t::eDataspaceChanged) {
3794 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3795 }
3796 if (what & layer_state_t::eHdrMetadataChanged) {
3797 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3798 }
3799 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3800 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3801 }
3802 if (what & layer_state_t::eApiChanged) {
3803 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3804 }
3805 if (what & layer_state_t::eSidebandStreamChanged) {
3806 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3807 }
Robert Carr720e5062018-07-30 17:45:14 -07003808 if (what & layer_state_t::eInputInfoChanged) {
3809 layer->setInputInfo(s.inputInfo);
3810 flags |= eTraversalNeeded;
3811 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003812 std::vector<sp<CallbackHandle>> callbackHandles;
3813 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3814 mTransactionCompletedThread.run();
3815 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3816 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3817 }
3818 }
3819 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3820 // Do not put anything that updates layer state or modifies flags after
3821 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003822 return flags;
3823}
3824
chaviw273171b2018-12-26 11:46:30 -08003825uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3826 uint32_t flags = 0;
3827 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3828 flags |= eTraversalNeeded;
3829 }
3830
3831 mInputWindowCommands.merge(inputWindowCommands);
3832 return flags;
3833}
3834
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003835status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003836 const String8& name,
3837 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003838 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003839 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003840 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003841{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003842 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003843 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003844 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003845 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003846 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003847
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003848 status_t result = NO_ERROR;
3849
3850 sp<Layer> layer;
3851
Cody Northropbc755282017-03-31 12:00:08 -06003852 String8 uniqueName = getUniqueLayerName(name);
3853
Mathias Agopian3165cc22012-08-08 19:42:09 -07003854 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003855 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003856 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3857 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003858
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003859 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003860 case ISurfaceComposerClient::eFXSurfaceBufferState:
3861 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3862 break;
chaviw13fdc492017-06-27 12:40:18 -07003863 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003864 // check if buffer size is set for color layer.
3865 if (w > 0 || h > 0) {
3866 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3867 int(w), int(h));
3868 return BAD_VALUE;
3869 }
3870
chaviw13fdc492017-06-27 12:40:18 -07003871 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003872 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003873 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003874 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003875 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003876 // check if buffer size is set for container layer.
3877 if (w > 0 || h > 0) {
3878 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3879 int(w), int(h));
3880 return BAD_VALUE;
3881 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003882 result = createContainerLayer(client,
3883 uniqueName, w, h, flags,
3884 handle, &layer);
3885 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003886 default:
3887 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003888 break;
3889 }
3890
Dan Stoza7d89d062015-04-30 13:29:25 -07003891 if (result != NO_ERROR) {
3892 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003893 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003894
Chia-I Wuab0c3192017-08-01 11:29:00 -07003895 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3896 // TODO b/64227542
3897 if (windowType == 441731) {
3898 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3899 layer->setPrimaryDisplayOnly();
3900 }
3901
Albert Chaulk479c60c2017-01-27 14:21:34 -05003902 layer->setInfo(windowType, ownerUid);
3903
Robert Carrb89ea9d2018-12-10 13:01:14 -08003904 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
3905 result = addClientLayer(client, *handle, *gbp, layer, *parent,
3906 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003907 if (result != NO_ERROR) {
3908 return result;
3909 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003910 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003911
3912 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003913 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003914}
3915
Cody Northropbc755282017-03-31 12:00:08 -06003916String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3917{
3918 bool matchFound = true;
3919 uint32_t dupeCounter = 0;
3920
3921 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3922 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3923
Dan Stoza436ccf32018-06-21 12:10:12 -07003924 // Grab the state lock since we're accessing mCurrentState
3925 Mutex::Autolock lock(mStateLock);
3926
Cody Northropbc755282017-03-31 12:00:08 -06003927 // Loop over layers until we're sure there is no matching name
3928 while (matchFound) {
3929 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003930 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003931 if (layer->getName() == uniqueName) {
3932 matchFound = true;
3933 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3934 }
3935 });
3936 }
3937
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003938 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3939 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003940
3941 return uniqueName;
3942}
3943
Marissa Wallfd668622018-05-10 10:21:13 -07003944status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3945 uint32_t w, uint32_t h, uint32_t flags,
3946 PixelFormat& format, sp<IBinder>* handle,
3947 sp<IGraphicBufferProducer>* gbp,
3948 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003949 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003950 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003951 case PIXEL_FORMAT_TRANSPARENT:
3952 case PIXEL_FORMAT_TRANSLUCENT:
3953 format = PIXEL_FORMAT_RGBA_8888;
3954 break;
3955 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003956 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003957 break;
3958 }
3959
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003960 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003961 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003962 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003963 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003964 *handle = layer->getHandle();
3965 *gbp = layer->getProducer();
3966 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003967 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003968
Marissa Wallfd668622018-05-10 10:21:13 -07003969 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003970 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003971}
3972
Marissa Wall61c58622018-07-18 10:12:20 -07003973status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3974 uint32_t w, uint32_t h, uint32_t flags,
3975 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003976 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003977 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003978 *handle = layer->getHandle();
3979 *outLayer = layer;
3980
3981 return NO_ERROR;
3982}
3983
chaviw13fdc492017-06-27 12:40:18 -07003984status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003985 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003986 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003987{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003988 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003989 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003990 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003991}
3992
Robert Carr6b3f6c52018-08-13 13:05:17 -07003993status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3994 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3995 sp<IBinder>* handle, sp<Layer>* outLayer)
3996{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003997 *outLayer =
3998 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003999 *handle = (*outLayer)->getHandle();
4000 return NO_ERROR;
4001}
4002
4003
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004004void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004005 mLayersPendingRemoval.add(layer);
4006 mLayersRemoved = true;
4007 setTransactionFlags(eTransactionNeeded);
4008}
4009
Robert Carr695d5282018-12-18 15:27:58 -08004010void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004011{
Robert Carr2e102c92018-10-23 12:11:15 -07004012 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004013 // If a layer has a parent, we allow it to out-live it's handle
4014 // with the idea that the parent holds a reference and will eventually
4015 // be cleaned up. However no one cleans up the top-level so we do so
4016 // here.
4017 if (layer->getParent() == nullptr) {
4018 mCurrentState.layersSortedByZ.remove(layer);
4019 }
4020 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004021 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004022}
4023
Mathias Agopianb60314a2012-04-10 22:09:54 -07004024// ---------------------------------------------------------------------------
4025
Andy McFadden13a082e2012-08-24 10:16:42 -07004026void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004027 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004028 if (!displayToken) return;
4029
Jesse Hall01e29052013-02-19 16:13:35 -08004030 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004031 Vector<ComposerState> state;
4032 Vector<DisplayState> displays;
4033 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004034 d.what = DisplayState::eDisplayProjectionChanged |
4035 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004036 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08004037 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004038 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004039 d.frame.makeInvalid();
4040 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004041 d.width = 0;
4042 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004043 displays.add(d);
chaviw273171b2018-12-26 11:46:30 -08004044 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004045
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004046 const auto display = getDisplayDevice(displayToken);
4047 if (!display) return;
4048
Dominik Laskowskie9774092018-12-11 10:04:24 -08004049 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004050
Dominik Laskowski075d3172018-05-24 15:50:06 -07004051 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08004052 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07004053 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004054
Brian Andersond0010582017-03-07 13:20:31 -08004055 // Use phase of 0 since phase is not known.
4056 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07004057 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
4058 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004059}
4060
4061void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004062 // Async since we may be called from the main thread.
4063 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004064}
4065
Dominik Laskowskie9774092018-12-11 10:04:24 -08004066void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004067 if (display->isVirtual()) {
4068 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004069 return;
4070 }
4071
Dominik Laskowski075d3172018-05-24 15:50:06 -07004072 const auto displayId = display->getId();
4073 LOG_ALWAYS_FATAL_IF(!displayId);
4074
Dominik Laskowski34157762018-10-31 13:07:19 -07004075 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004076
4077 int currentMode = display->getPowerMode();
4078 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004079 return;
4080 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004081
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004082 display->setPowerMode(mode);
4083
Lloyd Pique4dccc412018-01-22 17:21:36 -08004084 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004085 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004086 }
4087
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004088 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004089 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004090 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004091 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004092 if (mUseScheduler) {
4093 mScheduler->onScreenAcquired(mAppConnectionHandle);
4094 } else {
4095 mEventThread->onScreenAcquired();
4096 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004097 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004098 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004099
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004100 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004101 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004102 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004103
4104 struct sched_param param = {0};
4105 param.sched_priority = 1;
4106 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4107 ALOGW("Couldn't set SCHED_FIFO on display on");
4108 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004109 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004110 // Turn off the display
4111 struct sched_param param = {0};
4112 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4113 ALOGW("Couldn't set SCHED_OTHER on display off");
4114 }
4115
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004116 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004117 if (mUseScheduler) {
4118 mScheduler->disableHardwareVsync(true);
4119 } else {
4120 disableHardwareVsync(true); // also cancels any in-progress resync
4121 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004122 if (mUseScheduler) {
4123 mScheduler->onScreenReleased(mAppConnectionHandle);
4124 } else {
4125 mEventThread->onScreenReleased();
4126 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004127 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004128
Dominik Laskowski075d3172018-05-24 15:50:06 -07004129 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004130 mVisibleRegionsDirty = true;
4131 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004132 } else if (mode == HWC_POWER_MODE_DOZE ||
4133 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004134 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004135 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004136 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004137 if (mUseScheduler) {
4138 mScheduler->onScreenAcquired(mAppConnectionHandle);
4139 } else {
4140 mEventThread->onScreenAcquired();
4141 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004142 resyncToHardwareVsync(true);
4143 }
4144 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4145 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004146 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004147 if (mUseScheduler) {
4148 mScheduler->disableHardwareVsync(true);
4149 } else {
4150 disableHardwareVsync(true); // also cancels any in-progress resync
4151 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004152 if (mUseScheduler) {
4153 mScheduler->onScreenReleased(mAppConnectionHandle);
4154 } else {
4155 mEventThread->onScreenReleased();
4156 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004157 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004158 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004159 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004160 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004161 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004162 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004163
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004164 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004165 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004166 }
4167
Dominik Laskowski34157762018-10-31 13:07:19 -07004168 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004169}
4170
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004171void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004172 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004173 const auto display = getDisplayDevice(displayToken);
4174 if (!display) {
4175 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4176 displayToken.get());
4177 } else if (display->isVirtual()) {
4178 ALOGW("Attempt to set power mode %d for virtual display", mode);
4179 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004180 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004181 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004182 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004183}
4184
4185// ---------------------------------------------------------------------------
4186
Lloyd Pique755e3192018-01-31 16:46:15 -08004187status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4188 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004189 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004190
Mathias Agopianbd115332013-04-18 16:41:04 -07004191 IPCThreadState* ipc = IPCThreadState::self();
4192 const int pid = ipc->getCallingPid();
4193 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004194
Mathias Agopianbd115332013-04-18 16:41:04 -07004195 if ((uid != AID_SHELL) &&
4196 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004197 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4198 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004199 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004200 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004201 // (this would indicate SF is stuck, but we want to be able to
4202 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004203 status_t err = mStateLock.timedLock(s2ns(1));
4204 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004205 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004206 StringAppendF(&result,
4207 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4208 "(no locks held)\n",
4209 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004210 }
4211
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004212 bool dumpAll = true;
4213 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004214 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004215
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004216 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004217 if ((index < numArgs) &&
4218 (args[index] == String16("--list"))) {
4219 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004220 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004221 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004222 }
4223
4224 if ((index < numArgs) &&
4225 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004226 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004227 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004228 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004229 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004230
4231 if ((index < numArgs) &&
4232 (args[index] == String16("--latency-clear"))) {
4233 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004234 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004235 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004236 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004237
4238 if ((index < numArgs) &&
4239 (args[index] == String16("--dispsync"))) {
4240 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004241 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004242 dumpAll = false;
4243 }
Dan Stozab90cf072015-03-05 11:05:59 -08004244
4245 if ((index < numArgs) &&
4246 (args[index] == String16("--static-screen"))) {
4247 index++;
4248 dumpStaticScreenStats(result);
4249 dumpAll = false;
4250 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004251
4252 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004253 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004254 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004255 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004256 dumpAll = false;
4257 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004258
4259 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4260 index++;
4261 dumpWideColorInfo(result);
4262 dumpAll = false;
4263 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004264
4265 if ((index < numArgs) &&
4266 (args[index] == String16("--enable-layer-stats"))) {
4267 index++;
4268 mLayerStats.enable();
4269 dumpAll = false;
4270 }
4271
4272 if ((index < numArgs) &&
4273 (args[index] == String16("--disable-layer-stats"))) {
4274 index++;
4275 mLayerStats.disable();
4276 dumpAll = false;
4277 }
4278
4279 if ((index < numArgs) &&
4280 (args[index] == String16("--clear-layer-stats"))) {
4281 index++;
4282 mLayerStats.clear();
4283 dumpAll = false;
4284 }
4285
4286 if ((index < numArgs) &&
4287 (args[index] == String16("--dump-layer-stats"))) {
4288 index++;
4289 mLayerStats.dump(result);
4290 dumpAll = false;
4291 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004292
4293 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004294 (args[index] == String16("--frame-composition"))) {
4295 index++;
4296 dumpFrameCompositionInfo(result);
4297 dumpAll = false;
4298 }
4299
4300 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004301 (args[index] == String16("--display-identification"))) {
4302 index++;
4303 dumpDisplayIdentificationData(result);
4304 dumpAll = false;
4305 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004306
4307 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4308 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004309 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004310 dumpAll = false;
4311 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004312 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004313
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004314 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004315 if (asProto) {
4316 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4317 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4318 } else {
4319 dumpAllLocked(args, index, result);
4320 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004321 }
4322
Mathias Agopian9795c422009-08-26 16:36:26 -07004323 if (locked) {
4324 mStateLock.unlock();
4325 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004326 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004327 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004328 return NO_ERROR;
4329}
4330
Yiwei Zhang5434a782018-12-05 18:06:32 -08004331void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4332 std::string& result) const {
4333 mCurrentState.traverseInZOrder(
4334 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004335}
4336
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004337void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004338 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004339 String8 name;
4340 if (index < args.size()) {
4341 name = String8(args[index]);
4342 index++;
4343 }
4344
Dominik Laskowski075d3172018-05-24 15:50:06 -07004345 if (const auto displayId = getInternalDisplayId();
4346 displayId && getHwComposer().isConnected(*displayId)) {
4347 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004348 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004349 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004350 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004351
4352 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004353 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004354 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004355 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004356 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004357 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004358 }
Robert Carr2047fae2016-11-28 14:09:09 -08004359 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004360 }
4361}
4362
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004363void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004364 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004365 String8 name;
4366 if (index < args.size()) {
4367 name = String8(args[index]);
4368 index++;
4369 }
4370
Robert Carr2047fae2016-11-28 14:09:09 -08004371 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004372 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004373 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004374 }
Robert Carr2047fae2016-11-28 14:09:09 -08004375 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004376
Svetoslavd85084b2014-03-20 10:28:31 -07004377 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004378}
4379
Jamie Gennis6547ff42013-07-16 20:12:42 -07004380// This should only be called from the main thread. Otherwise it would need
4381// the lock and should use mCurrentState rather than mDrawingState.
4382void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004383 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004384 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004385 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004386
4387 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4388}
4389
Yiwei Zhang5434a782018-12-05 18:06:32 -08004390void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004391 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004392
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004393 if (isLayerTripleBufferingDisabled())
4394 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004395
Yiwei Zhang5434a782018-12-05 18:06:32 -08004396 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4397 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4398 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4399 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4400 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4401 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004402 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004403}
4404
Yiwei Zhang5434a782018-12-05 18:06:32 -08004405void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4406 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004407 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4408 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004409 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004410 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004411 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004412 }
David Sodman4a36e932017-11-07 14:29:47 -08004413 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004414 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004415 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004416 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4417 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004418}
4419
Dan Stozae77c7662016-05-13 11:37:28 -07004420void SurfaceFlinger::recordBufferingStats(const char* layerName,
4421 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004422 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4423 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004424 for (const auto& segment : history) {
4425 if (!segment.usedThirdBuffer) {
4426 stats.twoBufferTime += segment.totalTime;
4427 }
4428 if (segment.occupancyAverage < 1.0f) {
4429 stats.doubleBufferedTime += segment.totalTime;
4430 } else if (segment.occupancyAverage < 2.0f) {
4431 stats.tripleBufferedTime += segment.totalTime;
4432 }
4433 ++stats.numSegments;
4434 stats.totalTime += segment.totalTime;
4435 }
4436}
4437
Yiwei Zhang5434a782018-12-05 18:06:32 -08004438void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4439 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004440
4441 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4442 const size_t count = currentLayers.size();
4443 for (size_t i=0 ; i<count ; i++) {
4444 currentLayers[i]->dumpFrameEvents(result);
4445 }
4446}
4447
Yiwei Zhang5434a782018-12-05 18:06:32 -08004448void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004449 result.append("Buffering stats:\n");
4450 result.append(" [Layer name] <Active time> <Two buffer> "
4451 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004452 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004453 typedef std::tuple<std::string, float, float, float> BufferTuple;
4454 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004455 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004456 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004457 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004458 if (stats.numSegments == 0) {
4459 continue;
4460 }
4461 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4462 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4463 stats.totalTime;
4464 float doubleBufferRatio = static_cast<float>(
4465 stats.doubleBufferedTime) / stats.totalTime;
4466 float tripleBufferRatio = static_cast<float>(
4467 stats.tripleBufferedTime) / stats.totalTime;
4468 sorted.insert({activeTime, {name, twoBufferRatio,
4469 doubleBufferRatio, tripleBufferRatio}});
4470 }
4471 for (const auto& sortedPair : sorted) {
4472 float activeTime = sortedPair.first;
4473 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004474 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4475 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004476 }
4477 result.append("\n");
4478}
4479
Yiwei Zhang5434a782018-12-05 18:06:32 -08004480void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004481 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004482 const auto displayId = display->getId();
4483 if (!displayId) {
4484 continue;
4485 }
4486 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004487 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004488 continue;
4489 }
4490
Yiwei Zhang5434a782018-12-05 18:06:32 -08004491 StringAppendF(&result,
4492 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4493 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004494 uint8_t port;
4495 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004496 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004497 result.append("no identification data\n");
4498 continue;
4499 }
4500
4501 if (!isEdid(data)) {
4502 result.append("unknown identification data: ");
4503 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004504 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004505 }
4506 result.append("\n");
4507 continue;
4508 }
4509
4510 const auto edid = parseEdid(data);
4511 if (!edid) {
4512 result.append("invalid EDID: ");
4513 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004514 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004515 }
4516 result.append("\n");
4517 continue;
4518 }
4519
Yiwei Zhang5434a782018-12-05 18:06:32 -08004520 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004521 result.append(edid->displayName.data(), edid->displayName.length());
4522 result.append("\"\n");
4523 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004524}
4525
Yiwei Zhang5434a782018-12-05 18:06:32 -08004526void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4527 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4528 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4529 StringAppendF(&result, "DisplayColorSetting: %s\n",
4530 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004531
4532 // TODO: print out if wide-color mode is active or not
4533
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004534 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004535 const auto displayId = display->getId();
4536 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004537 continue;
4538 }
4539
Yiwei Zhang5434a782018-12-05 18:06:32 -08004540 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004541 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004542 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004543 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004544 }
4545
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004546 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004547 StringAppendF(&result, " Current color mode: %s (%d)\n",
4548 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004549 }
4550 result.append("\n");
4551}
4552
Yiwei Zhang5434a782018-12-05 18:06:32 -08004553void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004554 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004555 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4556 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004557 continue;
4558 }
4559
Dominik Laskowski05275f12018-11-01 15:03:24 -07004560 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004561 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4562 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004563 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004564 compositionInfo.dump(result, nullptr);
4565 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004566 }
4567 }
David Sodman7e4ae112018-02-09 15:02:28 -08004568}
4569
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004570LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004571 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004572 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4573 const State& state = useDrawing ? mDrawingState : mCurrentState;
4574 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004575 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004576 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004577 });
4578
4579 return layersProto;
4580}
4581
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004582LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004583 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004584
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004585 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004586 resolution->set_w(display.getWidth());
4587 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004588
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004589 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4590 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4591 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004592
Dominik Laskowski075d3172018-05-24 15:50:06 -07004593 const auto displayId = display.getId();
4594 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004595 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004596 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004597 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004598 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004599 }
4600 });
4601
4602 return layersProto;
4603}
4604
Mathias Agopian74d211a2013-04-22 16:55:35 +02004605void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004606 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004607 bool colorize = false;
4608 if (index < args.size()
4609 && (args[index] == String16("--color"))) {
4610 colorize = true;
4611 index++;
4612 }
4613
4614 Colorizer colorizer(colorize);
4615
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004616 // figure out if we're stuck somewhere
4617 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004618 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004619 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4620
4621 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004622 * Dump library configuration.
4623 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004624
4625 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004626 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004627 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004628 appendSfConfigString(result);
4629 appendUiConfigString(result);
4630 appendGuiConfigString(result);
4631 result.append("\n");
4632
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004633 result.append("\nDisplay identification data:\n");
4634 dumpDisplayIdentificationData(result);
4635
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004636 result.append("\nWide-Color information:\n");
4637 dumpWideColorInfo(result);
4638
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004639 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004640 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004641 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004642 result.append(SyncFeatures::getInstance().toString());
4643 result.append("\n");
4644
Andy McFadden41d67d72014-04-25 16:58:34 -07004645 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004646 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004647 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004648
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004649 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4650 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004651 if (const auto displayId = getInternalDisplayId();
4652 displayId && getHwComposer().isConnected(*displayId)) {
4653 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004654 StringAppendF(&result,
4655 "Display %s: app phase %" PRId64 " ns, "
4656 "sf phase %" PRId64 " ns, "
4657 "early app phase %" PRId64 " ns, "
4658 "early sf phase %" PRId64 " ns, "
4659 "early app gl phase %" PRId64 " ns, "
4660 "early sf gl phase %" PRId64 " ns, "
4661 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4662 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4663 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4664 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004665 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004666 result.append("\n");
4667
Dan Stozab90cf072015-03-05 11:05:59 -08004668 // Dump static screen stats
4669 result.append("\n");
4670 dumpStaticScreenStats(result);
4671 result.append("\n");
4672
Yiwei Zhang5434a782018-12-05 18:06:32 -08004673 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004674
Dan Stozae77c7662016-05-13 11:37:28 -07004675 dumpBufferingStats(result);
4676
Andy McFadden4803b742012-09-24 19:07:20 -07004677 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004678 * Dump the visible layer list
4679 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004680 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004681 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4682 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4683 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004684 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004685
Chia-I Wu2f884132018-09-13 15:17:58 -07004686 {
4687 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4688 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004689 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004690 result.append("\n");
4691 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004692
David Sodman7e4ae112018-02-09 15:02:28 -08004693 result.append("\nFrame-Composition information:\n");
4694 dumpFrameCompositionInfo(result);
4695 result.append("\n");
4696
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004697 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004698 * Dump Display state
4699 */
4700
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004701 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004702 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004703 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004704 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004705 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004706 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004707 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004708
4709 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004710 * Dump SurfaceFlinger global state
4711 */
4712
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004713 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004714 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004715 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004716
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004717 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004718
Dominik Laskowski075d3172018-05-24 15:50:06 -07004719 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004720 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004721 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4722 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004723 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004724 StringAppendF(&result,
4725 " transaction-flags : %08x\n"
4726 " gpu_to_cpu_unsupported : %d\n",
4727 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004728
Dominik Laskowski075d3172018-05-24 15:50:06 -07004729 if (const auto displayId = getInternalDisplayId();
4730 displayId && getHwComposer().isConnected(*displayId)) {
4731 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004732 StringAppendF(&result,
4733 " refresh-rate : %f fps\n"
4734 " x-dpi : %f\n"
4735 " y-dpi : %f\n",
4736 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4737 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004738 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004739
Yiwei Zhang5434a782018-12-05 18:06:32 -08004740 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004741
Yiwei Zhang5434a782018-12-05 18:06:32 -08004742 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004743 /*
4744 * VSYNC state
4745 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004746 if (mUseScheduler) {
4747 mScheduler->dump(mAppConnectionHandle, result);
4748 } else {
4749 mEventThread->dump(result);
4750 }
Dan Stozae22aec72016-08-01 13:20:59 -07004751 result.append("\n");
4752
4753 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004754 * Tracing state
4755 */
4756 mTracing.dump(result);
4757 result.append("\n");
4758
4759 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004760 * HWC layer minidump
4761 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004762 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004763 const auto displayId = display->getId();
4764 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004765 continue;
4766 }
4767
Yiwei Zhang5434a782018-12-05 18:06:32 -08004768 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004769 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004770 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004771 result.append("\n");
4772 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004773
4774 /*
4775 * Dump HWComposer state
4776 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004777 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004778 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004779 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004780 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004781 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004782 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004783
4784 /*
4785 * Dump gralloc state
4786 */
4787 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4788 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004789
4790 /*
4791 * Dump VrFlinger state if in use.
4792 */
4793 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4794 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004795 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004796 result.append("\n");
4797 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004798}
4799
Dominik Laskowski075d3172018-05-24 15:50:06 -07004800const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004801 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004802 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004803 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004804 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004805 }
4806 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004807
Dominik Laskowski34157762018-10-31 13:07:19 -07004808 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004809 static const Vector<sp<Layer>> empty;
4810 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004811}
4812
Keun young Park63f165f2012-08-31 10:53:36 -07004813bool SurfaceFlinger::startDdmConnection()
4814{
4815 void* libddmconnection_dso =
4816 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4817 if (!libddmconnection_dso) {
4818 return false;
4819 }
4820 void (*DdmConnection_start)(const char* name);
4821 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004822 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004823 if (!DdmConnection_start) {
4824 dlclose(libddmconnection_dso);
4825 return false;
4826 }
4827 (*DdmConnection_start)(getServiceName());
4828 return true;
4829}
4830
Chia-I Wu28f320b2018-05-03 11:02:56 -07004831void SurfaceFlinger::updateColorMatrixLocked() {
4832 mat4 colorMatrix;
4833 if (mGlobalSaturationFactor != 1.0f) {
4834 // Rec.709 luma coefficients
4835 float3 luminance{0.213f, 0.715f, 0.072f};
4836 luminance *= 1.0f - mGlobalSaturationFactor;
4837 mat4 saturationMatrix = mat4(
4838 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4839 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4840 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4841 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4842 );
4843 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4844 } else {
4845 colorMatrix = mClientColorMatrix * mDaltonizer();
4846 }
4847
4848 if (mCurrentState.colorMatrix != colorMatrix) {
4849 mCurrentState.colorMatrix = colorMatrix;
4850 mCurrentState.colorMatrixChanged = true;
4851 setTransactionFlags(eTransactionNeeded);
4852 }
4853}
4854
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004855status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004856#pragma clang diagnostic push
4857#pragma clang diagnostic error "-Wswitch-enum"
4858 switch (static_cast<ISurfaceComposerTag>(code)) {
4859 // These methods should at minimum make sure that the client requested
4860 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004861 case BOOT_FINISHED:
4862 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004863 case CREATE_DISPLAY:
4864 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004865 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004866 case GET_ACTIVE_COLOR_MODE:
4867 case GET_ANIMATION_FRAME_STATS:
4868 case GET_HDR_CAPABILITIES:
4869 case SET_ACTIVE_CONFIG:
4870 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004871 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004872 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004873 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004874 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4875 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004876 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4877 IPCThreadState* ipc = IPCThreadState::self();
4878 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4879 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004880 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004881 }
Robert Carr1db73f62016-12-21 12:58:51 -08004882 return OK;
4883 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004884 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004885 IPCThreadState* ipc = IPCThreadState::self();
4886 const int pid = ipc->getCallingPid();
4887 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004888 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4889 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004890 return PERMISSION_DENIED;
4891 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004892 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004893 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004894 // Used by apps to hook Choreographer to SurfaceFlinger.
4895 case CREATE_DISPLAY_EVENT_CONNECTION:
4896 // The following calls are currently used by clients that do not
4897 // request necessary permissions. However, they do not expose any secret
4898 // information, so it is OK to pass them.
4899 case AUTHENTICATE_SURFACE:
4900 case GET_ACTIVE_CONFIG:
4901 case GET_BUILT_IN_DISPLAY:
4902 case GET_DISPLAY_COLOR_MODES:
4903 case GET_DISPLAY_CONFIGS:
4904 case GET_DISPLAY_STATS:
4905 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4906 // Calling setTransactionState is safe, because you need to have been
4907 // granted a reference to Client* and Handle* to do anything with it.
4908 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004909 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004910 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004911 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004912 return OK;
4913 }
4914 case CAPTURE_LAYERS:
4915 case CAPTURE_SCREEN: {
4916 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004917 IPCThreadState* ipc = IPCThreadState::self();
4918 const int pid = ipc->getCallingPid();
4919 const int uid = ipc->getCallingUid();
4920 if ((uid != AID_GRAPHICS) &&
4921 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4922 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4923 return PERMISSION_DENIED;
4924 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004925 return OK;
4926 }
4927 // The following codes are deprecated and should never be allowed to access SF.
4928 case CONNECT_DISPLAY_UNUSED:
4929 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4930 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4931 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004932 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004933 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004934
4935 // These codes are used for the IBinder protocol to either interrogate the recipient
4936 // side of the transaction for its canonical interface descriptor or to dump its state.
4937 // We let them pass by default.
4938 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4939 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4940 code == IBinder::SYSPROPS_TRANSACTION) {
4941 return OK;
4942 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004943 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004944 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004945 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004946 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4947 return OK;
4948 }
4949 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4950 return PERMISSION_DENIED;
4951#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004952}
4953
Ana Krulec13be8ad2018-08-21 02:43:56 +00004954status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4955 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004956 status_t credentialCheck = CheckTransactCodeCredentials(code);
4957 if (credentialCheck != OK) {
4958 return credentialCheck;
4959 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004960
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004961 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4962 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004963 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004964 IPCThreadState* ipc = IPCThreadState::self();
4965 const int uid = ipc->getCallingUid();
4966 if (CC_UNLIKELY(uid != AID_SYSTEM
4967 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004968 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004969 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004970 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004971 return PERMISSION_DENIED;
4972 }
4973 int n;
4974 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004975 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004976 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004977 return NO_ERROR;
4978 case 1002: // SHOW_UPDATES
4979 n = data.readInt32();
4980 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004981 invalidateHwcGeometry();
4982 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004983 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004984 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004985 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004986 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004987 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004988 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004989 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004990 setTransactionFlags(
4991 eTransactionNeeded|
4992 eDisplayTransactionNeeded|
4993 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004994 return NO_ERROR;
4995 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004996 case 1006:{ // send empty update
4997 signalRefresh();
4998 return NO_ERROR;
4999 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005000 case 1008: // toggle use of hw composer
5001 n = data.readInt32();
5002 mDebugDisableHWC = n ? 1 : 0;
5003 invalidateHwcGeometry();
5004 repaintEverything();
5005 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005006 case 1009: // toggle use of transform hint
5007 n = data.readInt32();
5008 mDebugDisableTransformHint = n ? 1 : 0;
5009 invalidateHwcGeometry();
5010 repaintEverything();
5011 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005012 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005013 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005014 reply->writeInt32(0);
5015 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005016 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005017 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005018 return NO_ERROR;
5019 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005020 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005021 if (!display) {
5022 return NAME_NOT_FOUND;
5023 }
5024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005025 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005026 return NO_ERROR;
5027 }
5028 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005029 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005030 // daltonize
5031 n = data.readInt32();
5032 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005033 case 1:
5034 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5035 break;
5036 case 2:
5037 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5038 break;
5039 case 3:
5040 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5041 break;
5042 default:
5043 mDaltonizer.setType(ColorBlindnessType::None);
5044 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005045 }
5046 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005047 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005048 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005049 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005050 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005051
5052 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005053 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005054 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005055 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005056 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005057 // apply a color matrix
5058 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005059 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005060 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005061 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005062 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005063 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005064 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005065 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005066 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005067 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005068 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005069
5070 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5071 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005072 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005073 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5074 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5075 }
5076
Chia-I Wu28f320b2018-05-03 11:02:56 -07005077 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005078 return NO_ERROR;
5079 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005080 // This is an experimental interface
5081 // Needs to be shifted to proper binder interface when we productize
5082 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005083 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005084 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005085 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005086 return NO_ERROR;
5087 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005088 case 1017: {
5089 n = data.readInt32();
5090 mForceFullDamage = static_cast<bool>(n);
5091 return NO_ERROR;
5092 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005093 case 1018: { // Modify Choreographer's phase offset
5094 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005095 if (mUseScheduler) {
5096 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5097 } else {
5098 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5099 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005100 return NO_ERROR;
5101 }
5102 case 1019: { // Modify SurfaceFlinger's phase offset
5103 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005104 if (mUseScheduler) {
5105 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5106 } else {
5107 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5108 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005109 return NO_ERROR;
5110 }
Irvel468051e2016-06-13 16:44:44 -07005111 case 1020: { // Layer updates interceptor
5112 n = data.readInt32();
5113 if (n) {
5114 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005115 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005116 }
5117 else{
5118 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005119 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005120 }
5121 return NO_ERROR;
5122 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005123 case 1021: { // Disable HWC virtual displays
5124 n = data.readInt32();
5125 mUseHwcVirtualDisplays = !n;
5126 return NO_ERROR;
5127 }
Romain Guy0147a172017-06-01 13:53:56 -07005128 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005129 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005130 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005131
Chia-I Wu28f320b2018-05-03 11:02:56 -07005132 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005133 return NO_ERROR;
5134 }
Romain Guy54f154a2017-10-24 21:40:32 +01005135 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005136 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005137 invalidateHwcGeometry();
5138 repaintEverything();
5139 return NO_ERROR;
5140 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005141 // Deprecate, use 1030 to check whether the device is color managed.
5142 case 1024: {
5143 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005144 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005145 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005146 n = data.readInt32();
5147 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005148 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005149 mTracing.enable();
5150 doTracing("tracing.enable");
5151 reply->writeInt32(NO_ERROR);
5152 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005153 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005154 status_t err = mTracing.disable();
5155 reply->writeInt32(err);
5156 }
5157 return NO_ERROR;
5158 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005159 case 1026: { // Get layer tracing status
5160 reply->writeBool(mTracing.isEnabled());
5161 return NO_ERROR;
5162 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005163 // Is a DisplayColorSetting supported?
5164 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005165 const auto display = getDefaultDisplayDevice();
5166 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005167 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005168 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005169
5170 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5171 switch (setting) {
5172 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005173 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005174 break;
5175 case DisplayColorSetting::UNMANAGED:
5176 reply->writeBool(true);
5177 break;
5178 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005179 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005180 break;
5181 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005182 reply->writeBool(
5183 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005184 break;
5185 }
5186 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005187 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005188 // Is VrFlinger active?
5189 case 1028: {
5190 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005191 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005192 return NO_ERROR;
5193 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005194 // Is device color managed?
5195 case 1030: {
5196 reply->writeBool(useColorManagement);
5197 return NO_ERROR;
5198 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005199 // Override default composition data space
5200 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5201 // && adb shell stop zygote && adb shell start zygote
5202 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5203 // adb shell stop zygote && adb shell start zygote
5204 case 1031: {
5205 Mutex::Autolock _l(mStateLock);
5206 n = data.readInt32();
5207 if (n) {
5208 n = data.readInt32();
5209 if (n) {
5210 Dataspace dataspace = static_cast<Dataspace>(n);
5211 if (!validateCompositionDataspace(dataspace)) {
5212 return BAD_VALUE;
5213 }
5214 mDefaultCompositionDataspace = dataspace;
5215 }
5216 n = data.readInt32();
5217 if (n) {
5218 Dataspace dataspace = static_cast<Dataspace>(n);
5219 if (!validateCompositionDataspace(dataspace)) {
5220 return BAD_VALUE;
5221 }
5222 mWideColorGamutCompositionDataspace = dataspace;
5223 }
5224 } else {
5225 // restore composition data space.
5226 mDefaultCompositionDataspace = defaultCompositionDataspace;
5227 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5228 }
5229 return NO_ERROR;
5230 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005231 }
5232 }
5233 return err;
5234}
5235
Steven Thomas6d8110b2017-08-31 18:24:21 -07005236void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005237 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005238 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005239}
5240
Ana Krulec7d1d6832018-12-27 11:10:09 -08005241void SurfaceFlinger::repaintEverythingForHWC() {
5242 mRepaintEverything = true;
5243 mEventQueue->invalidateForHWC();
5244}
5245
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005246// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5247class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005248public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005249 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5250 ~WindowDisconnector() {
5251 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005252 }
5253
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005254private:
5255 ANativeWindow* mWindow;
5256 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005257};
5258
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005259status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005260 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5261 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005262 uint32_t reqWidth, uint32_t reqHeight,
5263 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005264 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005265 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005266
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005267 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005268
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005269 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5270
Chia-I Wu20261cb2018-08-23 12:55:44 -07005271 sp<DisplayDevice> display;
5272 {
5273 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005274
Chia-I Wu20261cb2018-08-23 12:55:44 -07005275 display = getDisplayDeviceLocked(displayToken);
5276 if (!display) return BAD_VALUE;
5277
Chia-I Wucb023152018-08-28 12:57:23 -07005278 // set the requested width/height to the logical display viewport size
5279 // by default
5280 if (reqWidth == 0 || reqHeight == 0) {
5281 reqWidth = uint32_t(display->getViewport().width());
5282 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005283 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005284 }
5285
Peiyong Lin0e003c92018-09-17 11:09:51 -07005286 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5287 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005288
5289 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005290 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005291 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5292 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005293}
5294
5295status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005296 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5297 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005298 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005299 ATRACE_CALL();
5300
5301 class LayerRenderArea : public RenderArea {
5302 public:
Robert Carr578038f2018-03-09 12:25:24 -08005303 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005304 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5305 bool childrenOnly)
5306 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005307 mLayer(layer),
5308 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005309 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005310 mFlinger(flinger),
5311 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005312 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005313 Rect getBounds() const override {
5314 const Layer::State& layerState(mLayer->getDrawingState());
5315 return mLayer->getBufferSize(layerState);
5316 }
Marissa Wall61c58622018-07-18 10:12:20 -07005317 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005318 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005319 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005320 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005321 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005322 }
chaviwa76b2712017-09-20 12:02:26 -07005323 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005324 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005325 Rect getSourceCrop() const override {
5326 if (mCrop.isEmpty()) {
5327 return getBounds();
5328 } else {
5329 return mCrop;
5330 }
5331 }
Robert Carr578038f2018-03-09 12:25:24 -08005332 class ReparentForDrawing {
5333 public:
5334 const sp<Layer>& oldParent;
5335 const sp<Layer>& newParent;
5336
5337 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5338 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005339 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005340 }
Robert Carr15eae092018-03-23 13:43:53 -07005341 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005342 };
5343
5344 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005345 const Rect sourceCrop = getSourceCrop();
5346 // no need to check rotation because there is none
5347 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5348 sourceCrop.height() != getReqHeight();
5349
Robert Carr578038f2018-03-09 12:25:24 -08005350 if (!mChildrenOnly) {
5351 mTransform = mLayer->getTransform().inverse();
5352 drawLayers();
5353 } else {
5354 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005355 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005356 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5357 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005358
5359 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5360 drawLayers();
5361 }
5362 }
chaviwa76b2712017-09-20 12:02:26 -07005363
chaviwa76b2712017-09-20 12:02:26 -07005364 private:
chaviw7206d492017-11-10 16:16:12 -08005365 const sp<Layer> mLayer;
5366 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005367
5368 // In the "childrenOnly" case we reparent the children to a screenshot
5369 // layer which has no properties set and which does not draw.
5370 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005371 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005372 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005373
5374 SurfaceFlinger* mFlinger;
5375 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005376 };
5377
5378 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5379 auto parent = layerHandle->owner.promote();
5380
Robert Carr2e102c92018-10-23 12:11:15 -07005381 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005382 ALOGE("captureLayers called with a removed parent");
5383 return NAME_NOT_FOUND;
5384 }
5385
Robert Carr578038f2018-03-09 12:25:24 -08005386 const int uid = IPCThreadState::self()->getCallingUid();
5387 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005388 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005389 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5390 return PERMISSION_DENIED;
5391 }
5392
chaviw7206d492017-11-10 16:16:12 -08005393 Rect crop(sourceCrop);
5394 if (sourceCrop.width() <= 0) {
5395 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005396 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005397 }
5398
5399 if (sourceCrop.height() <= 0) {
5400 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005401 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005402 }
5403
5404 int32_t reqWidth = crop.width() * frameScale;
5405 int32_t reqHeight = crop.height() * frameScale;
5406
Chia-I Wu20261cb2018-08-23 12:55:44 -07005407 // really small crop or frameScale
5408 if (reqWidth <= 0) {
5409 reqWidth = 1;
5410 }
5411 if (reqHeight <= 0) {
5412 reqHeight = 1;
5413 }
5414
Peiyong Lin0e003c92018-09-17 11:09:51 -07005415 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005416
Robert Carr578038f2018-03-09 12:25:24 -08005417 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005418 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5419 if (!layer->isVisible()) {
5420 return;
Robert Carr578038f2018-03-09 12:25:24 -08005421 } else if (childrenOnly && layer == parent.get()) {
5422 return;
chaviwa76b2712017-09-20 12:02:26 -07005423 }
5424 visitor(layer);
5425 });
5426 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005427 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005428}
5429
5430status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5431 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005432 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005433 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005434 bool useIdentityTransform) {
5435 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005436
Peiyong Lin0e003c92018-09-17 11:09:51 -07005437 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005438 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5439 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005440 *outBuffer =
5441 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5442 static_cast<android_pixel_format>(reqPixelFormat), 1,
5443 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005444
5445 // This mutex protects syncFd and captureResult for communication of the return values from the
5446 // main thread back to this Binder thread
5447 std::mutex captureMutex;
5448 std::condition_variable captureCondition;
5449 std::unique_lock<std::mutex> captureLock(captureMutex);
5450 int syncFd = -1;
5451 std::optional<status_t> captureResult;
5452
Robert Carr03480e22018-01-04 16:02:06 -08005453 const int uid = IPCThreadState::self()->getCallingUid();
5454 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5455
Dominik Laskowski8c001672018-05-30 16:52:06 -07005456 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005457 // If there is a refresh pending, bug out early and tell the binder thread to try again
5458 // after the refresh.
5459 if (mRefreshPending) {
5460 ATRACE_NAME("Skipping screenshot for now");
5461 std::unique_lock<std::mutex> captureLock(captureMutex);
5462 captureResult = std::make_optional<status_t>(EAGAIN);
5463 captureCondition.notify_one();
5464 return;
5465 }
5466
5467 status_t result = NO_ERROR;
5468 int fd = -1;
5469 {
5470 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005471 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005472 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5473 useIdentityTransform, forSystem, &fd);
5474 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005475 }
5476
5477 {
5478 std::unique_lock<std::mutex> captureLock(captureMutex);
5479 syncFd = fd;
5480 captureResult = std::make_optional<status_t>(result);
5481 captureCondition.notify_one();
5482 }
5483 });
5484
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005485 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005486 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005487 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005488 while (*captureResult == EAGAIN) {
5489 captureResult.reset();
5490 result = postMessageAsync(message);
5491 if (result != NO_ERROR) {
5492 return result;
5493 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005494 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005495 }
5496 result = *captureResult;
5497 }
5498
5499 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005500 sync_wait(syncFd, -1);
5501 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005502 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005503
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005504 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005505}
5506
chaviwa76b2712017-09-20 12:02:26 -07005507void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005508 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005509 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005510 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005511
Lloyd Pique144e1162017-12-20 16:44:52 -08005512 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005513
chaviwa76b2712017-09-20 12:02:26 -07005514 const auto reqWidth = renderArea.getReqWidth();
5515 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005516 const auto sourceCrop = renderArea.getSourceCrop();
5517 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005518
Peiyong Lin0e003c92018-09-17 11:09:51 -07005519 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005520 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005521
Mathias Agopian180f10d2013-04-10 22:55:41 -07005522 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005523 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005524
5525 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005526 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005527 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005528
chaviw50da5042018-04-09 13:49:37 -07005529 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005530 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005531 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005532
chaviwa76b2712017-09-20 12:02:26 -07005533 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005534 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005535 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005536 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005537 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005538}
5539
chaviwa76b2712017-09-20 12:02:26 -07005540status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5541 TraverseLayersFunction traverseLayers,
5542 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005543 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005544 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005545 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005546 ATRACE_CALL();
5547
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005548 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005549
5550 traverseLayers([&](Layer* layer) {
5551 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5552 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005553
Robert Carr03480e22018-01-04 16:02:06 -08005554 // We allow the system server to take screenshots of secure layers for
5555 // use in situations like the Screen-rotation animation and place
5556 // the impetus on WindowManager to not persist them.
5557 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005558 ALOGW("FB is protected: PERMISSION_DENIED");
5559 return PERMISSION_DENIED;
5560 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005561 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005562
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005563 // this binds the given EGLImage as a framebuffer for the
5564 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005565 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005566 if (bufferBond.getStatus() != NO_ERROR) {
5567 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005568 return INVALID_OPERATION;
5569 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005570
Dan Stozaabcda352017-06-01 14:37:39 -07005571 // this will in fact render into our dequeued buffer
5572 // via an FBO, which means we didn't have to create
5573 // an EGLSurface and therefore we're not
5574 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005575 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005576
Peiyong Linfb530cf2018-12-15 05:07:38 +00005577 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005578 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005579 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005580 }
Alec Mouri492bc572018-09-11 21:40:04 +00005581 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005582
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005583 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005584}
5585
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005586// ---------------------------------------------------------------------------
5587
Dan Stoza412903f2017-04-27 13:42:17 -07005588void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5589 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005590}
5591
Dan Stoza412903f2017-04-27 13:42:17 -07005592void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5593 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005594}
5595
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005596void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005597 const LayerVector::Visitor& visitor) {
5598 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005599 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005600 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005601 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005602 continue;
5603 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005604 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005605 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005606 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005607 return;
5608 }
chaviwa76b2712017-09-20 12:02:26 -07005609 if (!layer->isVisible()) {
5610 return;
5611 }
5612 visitor(layer);
5613 });
5614 }
5615}
5616
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005617}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005618
Lloyd Pique074e8122018-07-26 12:57:23 -07005619
Mathias Agopian3f844832013-08-07 21:24:32 -07005620#if defined(__gl_h_)
5621#error "don't include gl/gl.h in this file"
5622#endif
5623
5624#if defined(__gl2_h_)
5625#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005626#endif