blob: ec6d75fbdcadafb8217cef33698fca2efa69cf23 [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
458sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
459 const sp<IGraphicBufferProducer>& gbp) {
460 if (authenticateSurfaceTexture(gbp) == false) {
461 return nullptr;
462 }
463 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
464 if (layer == nullptr) {
465 return nullptr;
466 }
467
468 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800469}
470
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700471sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
472 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700473{
474 class DisplayToken : public BBinder {
475 sp<SurfaceFlinger> flinger;
476 virtual ~DisplayToken() {
477 // no more references, this display must be terminated
478 Mutex::Autolock _l(flinger->mStateLock);
479 flinger->mCurrentState.displays.removeItem(this);
480 flinger->setTransactionFlags(eDisplayTransactionNeeded);
481 }
482 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700483 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700484 : flinger(flinger) {
485 }
486 };
487
488 sp<BBinder> token = new DisplayToken(this);
489
490 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700491 // Display ID is assigned when virtual display is allocated by HWC.
492 DisplayDeviceState state;
493 state.isSecure = secure;
494 state.displayName = displayName;
495 mCurrentState.displays.add(token, state);
496 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 return token;
498}
499
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700500void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700501 Mutex::Autolock _l(mStateLock);
502
Dominik Laskowski075d3172018-05-24 15:50:06 -0700503 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
504 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700505 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700506 return;
507 }
508
Dominik Laskowski075d3172018-05-24 15:50:06 -0700509 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
510 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700511 ALOGE("destroyDisplay called for non-virtual display");
512 return;
513 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700514 mInterceptor->saveDisplayDeletion(state.sequenceId);
515 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700516 setTransactionFlags(eDisplayTransactionNeeded);
517}
518
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700520 std::optional<DisplayId> displayId;
521
522 if (id == HWC_DISPLAY_PRIMARY) {
523 displayId = getInternalDisplayId();
524 } else if (id == HWC_DISPLAY_EXTERNAL) {
525 displayId = getExternalDisplayId();
526 }
527
528 if (!displayId) {
529 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800530 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700531 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700532
533 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700534}
535
Ady Abraham37965d42018-11-01 13:43:32 -0700536status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
537 if (!outGetColorManagement) {
538 return BAD_VALUE;
539 }
540 *outGetColorManagement = useColorManagement;
541 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700542}
543
Lloyd Pique441d5042018-10-18 16:49:51 -0700544HWComposer& SurfaceFlinger::getHwComposer() const {
545 return mCompositionEngine->getHwComposer();
546}
547
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700548renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
549 return mCompositionEngine->getRenderEngine();
550}
551
Lloyd Pique70d91362018-10-18 16:02:55 -0700552compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
553 return *mCompositionEngine.get();
554}
555
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800556void SurfaceFlinger::bootFinished()
557{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700558 if (mStartPropertySetThread->join() != NO_ERROR) {
559 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800560 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800561 const nsecs_t now = systemTime();
562 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000563 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700564
565 // wait patiently for the window manager death
566 const String16 name("window");
567 sp<IBinder> window(defaultServiceManager()->getService(name));
568 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700569 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700570 }
Robert Carr720e5062018-07-30 17:45:14 -0700571 sp<IBinder> input(defaultServiceManager()->getService(
572 String16("inputflinger")));
573 if (input == nullptr) {
574 ALOGE("Failed to link to input service");
575 } else {
576 mInputFlinger = interface_cast<IInputFlinger>(input);
577 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700578
Steven Thomas050b2c82017-03-06 11:45:16 -0800579 if (mVrFlinger) {
580 mVrFlinger->OnBootFinished();
581 }
582
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700583 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700584 // formerly we would just kill the process, but we now ask it to exit so it
585 // can choose where to stop the animation.
586 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700587
588 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
589 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
590 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700591
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800592 postMessageAsync(new LambdaMessage([this] {
593 readPersistentProperties();
594 mBootStage = BootStage::FINISHED;
595 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800596}
597
Dan Stoza436ccf32018-06-21 12:10:12 -0700598uint32_t SurfaceFlinger::getNewTexture() {
599 {
600 std::lock_guard lock(mTexturePoolMutex);
601 if (!mTexturePool.empty()) {
602 uint32_t name = mTexturePool.back();
603 mTexturePool.pop_back();
604 ATRACE_INT("TexturePoolSize", mTexturePool.size());
605 return name;
606 }
607
608 // The pool was too small, so increase it for the future
609 ++mTexturePoolSize;
610 }
611
612 // The pool was empty, so we need to get a new texture name directly using a
613 // blocking call to the main thread
614 uint32_t name = 0;
615 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
616 return name;
617}
618
Mathias Agopian3f844832013-08-07 21:24:32 -0700619void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700620 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700621}
622
Wei Wangf9b05ee2017-07-19 20:59:39 -0700623// Do not call property_set on main thread which will be blocked by init
624// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700625void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700626 ALOGI( "SurfaceFlinger's main thread ready to run. "
627 "Initializing graphics H/W...");
628
Thierry Strudel2924d012017-08-14 15:19:37 -0700629 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900630
Steven Thomasb02664d2017-07-26 18:48:28 -0700631 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800632
Steven Thomasb02664d2017-07-26 18:48:28 -0700633 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700634 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700635 mScheduler = getFactory().createScheduler([this](bool enabled) {
636 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
637 });
638
Ana Krulec98b5b242018-08-10 15:03:23 -0700639 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700640 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700641 [this] { resyncWithRateLimit(); },
642 impl::EventThread::InterceptVSyncsCallback());
643 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700644 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700645 [this] { resyncWithRateLimit(); },
646 [this](nsecs_t timestamp) {
647 mInterceptor->saveVSyncEvent(timestamp);
648 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800649
Ana Krulec98b5b242018-08-10 15:03:23 -0700650 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700651 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
652 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700653 } else {
654 mEventThreadSource =
655 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
656 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
657 mEventThread =
658 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
659 [this] { resyncWithRateLimit(); },
660 impl::EventThread::InterceptVSyncsCallback(),
661 "appEventThread");
662 mSfEventThreadSource =
663 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
664 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
665
666 mSFEventThread =
667 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
668 [this] { resyncWithRateLimit(); },
669 [this](nsecs_t timestamp) {
670 mInterceptor->saveVSyncEvent(timestamp);
671 },
672 "sfEventThread");
673 mEventQueue->setEventThread(mSFEventThread.get());
674 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
675 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800676
Steven Thomasb02664d2017-07-26 18:48:28 -0700677 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700678 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700679 renderEngineFeature |= (useColorManagement ?
680 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700681 renderEngineFeature |= (useContextPriority ?
682 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700683
684 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700685 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700686 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700687 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700688
689 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
690 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700691 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
692 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800693 // Process any initial hotplug and resulting display changes.
694 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700695 const auto display = getDefaultDisplayDeviceLocked();
696 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700697 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700698 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800699
Steven Thomas050b2c82017-03-06 11:45:16 -0800700 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700701 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700702 // This callback is called from the vr flinger dispatch thread. We
703 // need to call signalTransaction(), which requires holding
704 // mStateLock when we're not on the main thread. Acquiring
705 // mStateLock from the vr flinger dispatch thread might trigger a
706 // deadlock in surface flinger (see b/66916578), so post a message
707 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700708 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700709 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
710 mVrFlingerRequestsDisplay = requestDisplay;
711 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700712 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800713 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700714 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
715 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700716 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700717 .value_or(0),
718 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800719 if (!mVrFlinger) {
720 ALOGE("Failed to start vrflinger");
721 }
722 }
723
Lloyd Pique90c115d2018-09-18 21:39:42 -0700724 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700725 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700726
Mathias Agopian92a979a2012-08-02 18:32:23 -0700727 // initialize our drawing state
728 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700729
Andy McFadden13a082e2012-08-24 10:16:42 -0700730 // set initial conditions (e.g. unblank default device)
731 initializeDisplays();
732
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700733 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700734
Wei Wangf9b05ee2017-07-19 20:59:39 -0700735 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700736
737 const bool presentFenceReliable =
738 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
739 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700740
741 if (mStartPropertySetThread->Start() != NO_ERROR) {
742 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800743 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800744
Dan Stoza9e56aa02015-11-02 13:00:03 -0800745 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700746}
747
Romain Guy11d63f42017-07-20 12:47:14 -0700748void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700749 Mutex::Autolock _l(mStateLock);
750
Romain Guy11d63f42017-07-20 12:47:14 -0700751 char value[PROPERTY_VALUE_MAX];
752
753 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800754 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700755 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800756 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100757
758 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700759 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700760}
761
Mathias Agopiana67e4182012-06-19 17:26:12 -0700762void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800763 // Start boot animation service by setting a property mailbox
764 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700765 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800766 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700767 if (mStartPropertySetThread->join() != NO_ERROR) {
768 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800769 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700770}
771
Mathias Agopian875d8e12013-06-07 15:35:48 -0700772size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700773 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700774}
775
Mathias Agopian875d8e12013-06-07 15:35:48 -0700776size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700777 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700778}
779
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800780// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800781
Jamie Gennis582270d2011-08-17 18:19:00 -0700782bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800783 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800784 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800785 return authenticateSurfaceTextureLocked(bufferProducer);
786}
787
788bool SurfaceFlinger::authenticateSurfaceTextureLocked(
789 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800790 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800791 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800792}
793
Brian Anderson6b376712017-04-04 10:51:39 -0700794status_t SurfaceFlinger::getSupportedFrameTimestamps(
795 std::vector<FrameEvent>* outSupported) const {
796 *outSupported = {
797 FrameEvent::REQUESTED_PRESENT,
798 FrameEvent::ACQUIRE,
799 FrameEvent::LATCH,
800 FrameEvent::FIRST_REFRESH_START,
801 FrameEvent::LAST_REFRESH_START,
802 FrameEvent::GPU_COMPOSITION_DONE,
803 FrameEvent::DEQUEUE_READY,
804 FrameEvent::RELEASE,
805 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700806 ConditionalLock _l(mStateLock,
807 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700808 if (!getHwComposer().hasCapability(
809 HWC2::Capability::PresentFenceIsNotReliable)) {
810 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
811 }
812 return NO_ERROR;
813}
814
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700815status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
816 Vector<DisplayInfo>* configs) {
817 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700818 return BAD_VALUE;
819 }
820
Dominik Laskowski075d3172018-05-24 15:50:06 -0700821 const auto displayId = getPhysicalDisplayId(displayToken);
822 if (!displayId) {
823 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700824 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 // TODO: Not sure if display density should handled by SF any longer
827 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700828 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700830 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800831 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700832 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 }
834 return density;
835 }
836 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700839 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 return getDensityFromProperty("ro.sf.lcd_density"); }
841 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700842
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700844
Steven Thomas6d8110b2017-08-31 18:24:21 -0700845 ConditionalLock _l(mStateLock,
846 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700847 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 DisplayInfo info = DisplayInfo();
849
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850 float xdpi = hwConfig->getDpiX();
851 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700852
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700853 info.w = hwConfig->getWidth();
854 info.h = hwConfig->getHeight();
855 // Default display viewport to display width and height
856 info.viewportW = info.w;
857 info.viewportH = info.h;
858
Dominik Laskowski075d3172018-05-24 15:50:06 -0700859 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 // The density of the device is provided by a build property
861 float density = Density::getBuildDensity() / 160.0f;
862 if (density == 0) {
863 // the build doesn't provide a density -- this is wrong!
864 // use xdpi instead
865 ALOGE("ro.sf.lcd_density must be defined as a build property");
866 density = xdpi / 160.0f;
867 }
868 if (Density::getEmuDensity()) {
869 // if "qemu.sf.lcd_density" is specified, it overrides everything
870 xdpi = ydpi = density = Density::getEmuDensity();
871 density /= 160.0f;
872 }
873 info.density = density;
874
875 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700876 const auto display = getDefaultDisplayDeviceLocked();
877 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700878
879 // This is for screenrecord
880 const Rect viewport = display->getViewport();
881 if (viewport.isValid()) {
882 info.viewportW = uint32_t(viewport.getWidth());
883 info.viewportH = uint32_t(viewport.getHeight());
884 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700885 } else {
886 // TODO: where should this value come from?
887 static const int TV_DENSITY = 213;
888 info.density = TV_DENSITY / 160.0f;
889 info.orientation = 0;
890 }
891
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 info.xdpi = xdpi;
893 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900895 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896
Andy McFadden91b2ca82014-06-13 14:04:23 -0700897 // This is how far in advance a buffer must be queued for
898 // presentation at a given time. If you want a buffer to appear
899 // on the screen at time N, you must submit the buffer before
900 // (N - presentationDeadline).
901 //
902 // Normally it's one full refresh period (to give SF a chance to
903 // latch the buffer), but this can be reduced by configuring a
904 // DispSync offset. Any additional delays introduced by the hardware
905 // composer or panel must be accounted for here.
906 //
907 // We add an additional 1ms to allow for processing time and
908 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800909 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800910 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700911
912 // All non-virtual displays are currently considered secure.
913 info.secure = true;
914
Dominik Laskowski075d3172018-05-24 15:50:06 -0700915 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700916 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800917 std::swap(info.w, info.h);
918 }
919
Michael Wright28f24d02016-07-12 13:30:53 -0700920 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700921 }
922
Dan Stoza7f7da322014-05-02 15:26:25 -0700923 return NO_ERROR;
924}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700925
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700926status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
927 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700928 return BAD_VALUE;
929 }
930
Ana Krulece588e312018-09-18 12:32:24 -0700931 if (mUseScheduler) {
932 mScheduler->getDisplayStatInfo(stats);
933 } else {
934 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
935 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
936 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700937 return NO_ERROR;
938}
939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
941 const auto display = getDisplayDevice(displayToken);
942 if (!display) {
943 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800944 return BAD_VALUE;
945 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700946
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700948}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700949
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700950void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700951 if (display->isVirtual()) {
952 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
953 return;
954 }
955
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700956 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700957 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700958 return;
959 }
960
Dominik Laskowski075d3172018-05-24 15:50:06 -0700961 const auto displayId = display->getId();
962 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700963
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700964 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700965 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700966}
967
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700968status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700969 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700970 Vector<DisplayInfo> configs;
971 getDisplayConfigs(displayToken, &configs);
972 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
973 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
974 configs.size());
975 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700976 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700977 const auto display = getDisplayDevice(displayToken);
978 if (!display) {
979 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
980 displayToken.get());
981 } else if (display->isVirtual()) {
982 ALOGW("Attempt to set active config %d for virtual display", mode);
983 } else {
984 setActiveConfigInternal(display, mode);
985 }
986 }));
987
Mathias Agopian888c8222012-08-04 21:10:38 -0700988 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700989}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700990
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700991status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
992 Vector<ColorMode>* outColorModes) {
993 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700994 return BAD_VALUE;
995 }
996
Dominik Laskowski075d3172018-05-24 15:50:06 -0700997 const auto displayId = getPhysicalDisplayId(displayToken);
998 if (!displayId) {
999 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001000 }
1001
Peiyong Lina52f0292018-03-14 17:26:31 -07001002 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001003 {
1004 ConditionalLock _l(mStateLock,
1005 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001006 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001007 }
Michael Wright28f24d02016-07-12 13:30:53 -07001008 outColorModes->clear();
1009 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1010
1011 return NO_ERROR;
1012}
1013
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001014ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1015 if (const auto display = getDisplayDevice(displayToken)) {
1016 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001017 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001019}
1020
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001021void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1022 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001023 if (display->isVirtual()) {
1024 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1025 return;
1026 }
1027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001028 ColorMode currentMode = display->getActiveColorMode();
1029 Dataspace currentDataSpace = display->getCompositionDataSpace();
1030 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001031
Peiyong Lin38e9a562018-04-10 16:24:20 -07001032 if (mode == currentMode && dataSpace == currentDataSpace &&
1033 renderIntent == currentRenderIntent) {
1034 return;
1035 }
1036
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001037 display->setActiveColorMode(mode);
1038 display->setCompositionDataSpace(dataSpace);
1039 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001040
Dominik Laskowski075d3172018-05-24 15:50:06 -07001041 const auto displayId = display->getId();
1042 LOG_ALWAYS_FATAL_IF(!displayId);
1043 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1044
Dominik Laskowski34157762018-10-31 13:07:19 -07001045 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001046 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001047 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001048}
1049
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001051 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001052 Vector<ColorMode> modes;
1053 getDisplayColorModes(displayToken, &modes);
1054 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1055 if (mode < ColorMode::NATIVE || !exists) {
1056 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1057 decodeColorMode(mode).c_str(), mode, displayToken.get());
1058 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001059 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001060 const auto display = getDisplayDevice(displayToken);
1061 if (!display) {
1062 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1063 decodeColorMode(mode).c_str(), mode, displayToken.get());
1064 } else if (display->isVirtual()) {
1065 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1066 decodeColorMode(mode).c_str(), mode);
1067 } else {
1068 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1069 RenderIntent::COLORIMETRIC);
1070 }
1071 }));
1072
Michael Wright28f24d02016-07-12 13:30:53 -07001073 return NO_ERROR;
1074}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001075
Svetoslavd85084b2014-03-20 10:28:31 -07001076status_t SurfaceFlinger::clearAnimationFrameStats() {
1077 Mutex::Autolock _l(mStateLock);
1078 mAnimFrameTracker.clearStats();
1079 return NO_ERROR;
1080}
1081
1082status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1083 Mutex::Autolock _l(mStateLock);
1084 mAnimFrameTracker.getStats(outStats);
1085 return NO_ERROR;
1086}
1087
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001088status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1089 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001090 Mutex::Autolock _l(mStateLock);
1091
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001092 const auto display = getDisplayDeviceLocked(displayToken);
1093 if (!display) {
1094 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001095 return BAD_VALUE;
1096 }
1097
Peiyong Linfb069302018-04-25 14:34:31 -07001098 // At this point the DisplayDeivce should already be set up,
1099 // meaning the luminance information is already queried from
1100 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001101 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001102 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1103 capabilities.getDesiredMaxLuminance(),
1104 capabilities.getDesiredMaxAverageLuminance(),
1105 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001106
1107 return NO_ERROR;
1108}
1109
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001110status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1111 ui::PixelFormat* outFormat,
1112 ui::Dataspace* outDataspace,
1113 uint8_t* outComponentMask) const {
1114 if (!outFormat || !outDataspace || !outComponentMask) {
1115 return BAD_VALUE;
1116 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001117 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001118 if (!display || !display->getId()) {
1119 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1120 return BAD_VALUE;
1121 }
1122 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1123 outDataspace, outComponentMask);
1124}
1125
Kevin DuBois74e53772018-11-19 10:52:38 -08001126status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1127 bool enable, uint8_t componentMask,
1128 uint64_t maxFrames) const {
1129 const auto display = getDisplayDevice(displayToken);
1130 if (!display || !display->getId()) {
1131 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1132 return BAD_VALUE;
1133 }
1134
1135 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1136 componentMask, maxFrames);
1137}
1138
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001139status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1140 uint64_t maxFrames, uint64_t timestamp,
1141 DisplayedFrameStats* outStats) const {
1142 const auto display = getDisplayDevice(displayToken);
1143 if (!display || !display->getId()) {
1144 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1145 return BAD_VALUE;
1146 }
1147
1148 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1149 outStats);
1150}
1151
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001152status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001153 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001154 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001155
Chia-I Wu90f669f2017-10-05 14:24:41 -07001156 if (mInjectVSyncs == enable) {
1157 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001158 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001159
Ana Krulec98b5b242018-08-10 15:03:23 -07001160 // TODO(akrulec): Part of the Injector should be refactored, so that it
1161 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001162 if (enable) {
1163 ALOGV("VSync Injections enabled");
1164 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001165 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001166 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001167 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001168 impl::EventThread::InterceptVSyncsCallback(),
1169 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001170 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001171 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001172 } else {
1173 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001174 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001175 }
1176
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001177 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001178 }));
1179
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001180 return NO_ERROR;
1181}
1182
1183status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001184 Mutex::Autolock _l(mStateLock);
1185
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001186 if (!mInjectVSyncs) {
1187 ALOGE("VSync Injections not enabled");
1188 return BAD_VALUE;
1189 }
1190 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1191 ALOGV("Injecting VSync inside SurfaceFlinger");
1192 mVSyncInjector->onInjectSyncEvent(when);
1193 }
1194 return NO_ERROR;
1195}
1196
Lloyd Pique755e3192018-01-31 16:46:15 -08001197status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1198 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001199 // Try to acquire a lock for 1s, fail gracefully
1200 const status_t err = mStateLock.timedLock(s2ns(1));
1201 const bool locked = (err == NO_ERROR);
1202 if (!locked) {
1203 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1204 return TIMED_OUT;
1205 }
1206
1207 outLayers->clear();
1208 mCurrentState.traverseInZOrder([&](Layer* layer) {
1209 outLayers->push_back(layer->getLayerDebugInfo());
1210 });
1211
1212 mStateLock.unlock();
1213 return NO_ERROR;
1214}
1215
Peiyong Linc6780972018-10-28 15:24:08 -07001216status_t SurfaceFlinger::getCompositionPreference(
1217 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1218 Dataspace* outWideColorGamutDataspace,
1219 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001220 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001221 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001222 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001223 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001224 return NO_ERROR;
1225}
1226
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001227// ----------------------------------------------------------------------------
1228
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001229sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1230 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001231 if (mUseScheduler) {
1232 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1233 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1234 } else {
1235 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1236 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001237 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001238 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1239 return mSFEventThread->createEventConnection();
1240 } else {
1241 return mEventThread->createEventConnection();
1242 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001243 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001244}
1245
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001246// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001247
1248void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001249 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001250}
1251
1252void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001253 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001254}
1255
1256void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001257 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001258}
1259
1260void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001261 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001262 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001263}
1264
1265status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001266 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001267 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001268}
1269
1270status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001271 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001272 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001273 if (res == NO_ERROR) {
1274 msg->wait();
1275 }
1276 return res;
1277}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001278
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001279void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001280 do {
1281 waitForEvent();
1282 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001283}
1284
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001285void SurfaceFlinger::enableHardwareVsync() {
1286 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001287 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001288 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001289 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001290 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001291 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001292}
1293
Jesse Hall948fe0c2013-10-14 12:56:09 -07001294void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001295 Mutex::Autolock _l(mHWVsyncLock);
1296
Jesse Hall948fe0c2013-10-14 12:56:09 -07001297 if (makeAvailable) {
1298 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001299 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1300 if (mUseScheduler) {
1301 mScheduler->makeHWSyncAvailable(true);
1302 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001303 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001304 // Hardware vsync is not currently available, so abort the resync
1305 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001306 return;
1307 }
1308
Dominik Laskowski075d3172018-05-24 15:50:06 -07001309 const auto displayId = getInternalDisplayId();
1310 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001311 return;
1312 }
1313
Dominik Laskowski075d3172018-05-24 15:50:06 -07001314 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001315 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001316
Ana Krulece588e312018-09-18 12:32:24 -07001317 if (mUseScheduler) {
1318 mScheduler->setVsyncPeriod(period);
1319 } else {
1320 mPrimaryDispSync->reset();
1321 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001322
Ana Krulece588e312018-09-18 12:32:24 -07001323 if (!mPrimaryHWVsyncEnabled) {
1324 mPrimaryDispSync->beginResync();
1325 mEventControlThread->setVsyncEnabled(true);
1326 mPrimaryHWVsyncEnabled = true;
1327 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001328 }
1329}
1330
Jesse Hall948fe0c2013-10-14 12:56:09 -07001331void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001332 Mutex::Autolock _l(mHWVsyncLock);
1333 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001334 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001335 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001336 mPrimaryHWVsyncEnabled = false;
1337 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001338 if (makeUnavailable) {
1339 mHWVsyncAvailable = false;
1340 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001341}
1342
Tim Murray4a4e4a22016-04-19 16:29:23 +00001343void SurfaceFlinger::resyncWithRateLimit() {
1344 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001345
1346 // No explicit locking is needed here since EventThread holds a lock while calling this method
1347 static nsecs_t sLastResyncAttempted = 0;
1348 const nsecs_t now = systemTime();
1349 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001350 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001351 }
Dan Stoza57164302017-05-08 14:03:54 -07001352 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001353}
1354
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001355void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1356 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001357 ATRACE_NAME("SF onVsync");
1358
Steven Thomas3cfac282017-02-06 12:29:30 -08001359 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001361 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 return;
1363 }
1364
Dominik Laskowski075d3172018-05-24 15:50:06 -07001365 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001366 return;
1367 }
1368
Dominik Laskowski075d3172018-05-24 15:50:06 -07001369 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001370 // For now, we don't do anything with external display vsyncs.
1371 return;
1372 }
1373
Ana Krulece588e312018-09-18 12:32:24 -07001374 if (mUseScheduler) {
1375 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001376 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001377 bool needsHwVsync = false;
1378 { // Scope for the lock
1379 Mutex::Autolock _l(mHWVsyncLock);
1380 if (mPrimaryHWVsyncEnabled) {
1381 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1382 }
1383 }
1384
1385 if (needsHwVsync) {
1386 enableHardwareVsync();
1387 } else {
1388 disableHardwareVsync(false);
1389 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001390 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001391}
1392
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001393void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001394 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1395 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001396}
1397
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001398void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001399 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001400 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001401 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402
Lloyd Piqueba04e622017-12-14 17:11:26 -08001403 // Ignore events that do not have the right sequenceId.
1404 if (sequenceId != getBE().mComposerSequenceId) {
1405 return;
1406 }
1407
Steven Thomasb02664d2017-07-26 18:48:28 -07001408 // Only lock if we're not on the main thread. This function is normally
1409 // called on a hwbinder thread, but for the primary display it's called on
1410 // the main thread with the state lock already held, so don't attempt to
1411 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001412 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001413
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001414 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001415
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001416 if (std::this_thread::get_id() == mMainThreadId) {
1417 // Process all pending hot plug events immediately if we are on the main thread.
1418 processDisplayHotplugEventsLocked();
1419 }
1420
Lloyd Piqueba04e622017-12-14 17:11:26 -08001421 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001422}
1423
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001424void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001425 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001426 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001428 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001429 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001430}
1431
Dominik Laskowski075d3172018-05-24 15:50:06 -07001432void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001433 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001434 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001435 if (const auto displayId = getInternalDisplayId()) {
1436 getHwComposer().setVsyncEnabled(*displayId,
1437 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1438 }
Mathias Agopian86303202012-07-24 22:46:10 -07001439}
1440
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001442void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001443 if (mUseScheduler) {
1444 mScheduler->disableHardwareVsync(true);
1445 } else {
1446 disableHardwareVsync(true);
1447 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001448 // Clear the drawing state so that the logic inside of
1449 // handleTransactionLocked will fire. It will determine the delta between
1450 // mCurrentState and mDrawingState and re-apply all changes when we make the
1451 // transition.
1452 mDrawingState.displays.clear();
1453 mDisplays.clear();
1454}
1455
Steven Thomas050b2c82017-03-06 11:45:16 -08001456void SurfaceFlinger::updateVrFlinger() {
1457 if (!mVrFlinger)
1458 return;
1459 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001460 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001461 return;
1462 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001463
Lloyd Pique441d5042018-10-18 16:49:51 -07001464 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001465 ALOGE("Vr flinger is only supported for remote hardware composer"
1466 " service connections. Ignoring request to transition to vr"
1467 " flinger.");
1468 mVrFlingerRequestsDisplay = false;
1469 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001470 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001471
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001472 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001473
Steven Thomas0123ac62018-07-12 11:32:34 -07001474 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001475 LOG_ALWAYS_FATAL_IF(!display);
1476 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001477 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1478 // called below. Clear the reference now so we don't accidentally use it
1479 // later.
1480 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001481
Steven Thomasb02664d2017-07-26 18:48:28 -07001482 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001483 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001484 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001485
Steven Thomasb02664d2017-07-26 18:48:28 -07001486 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001487 // Delete the current instance before creating the new one
1488 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1489 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1490 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1491 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001492
Lloyd Pique441d5042018-10-18 16:49:51 -07001493 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001494 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001495
1496 if (vrFlingerRequestsDisplay) {
1497 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001498 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001499
1500 mVisibleRegionsDirty = true;
1501 invalidateHwcGeometry();
1502
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001503 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001504 display = getDefaultDisplayDeviceLocked();
1505 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001506 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001507
Steven Thomasb02664d2017-07-26 18:48:28 -07001508 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001509 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001510 const nsecs_t period = activeConfig->getVsyncPeriod();
1511 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001512
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001513 // The present fences returned from vr_hwc are not an accurate
1514 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001515 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001516 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1517 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001518 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001519 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001520 !hasSyncFramework);
1521 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001522
Steven Thomasb02664d2017-07-26 18:48:28 -07001523 // Use phase of 0 since phase is not known.
1524 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001525 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1526 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001527
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001528 resyncToHardwareVsync(false);
1529
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001530 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001531 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001532}
1533
Mathias Agopian4fec8732012-06-29 14:12:52 -07001534void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001535 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001536 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001537 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001538 if (mUseScheduler) {
1539 // This call is made each time SF wakes up and creates a new frame.
1540 mScheduler->incrementFrameCounter();
1541 }
Dan Stoza50182882016-07-08 12:02:20 -07001542 bool frameMissed = !mHadClientComposition &&
1543 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001544 (mPreviousPresentFence->getSignalTime() ==
1545 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001546 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001547 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001548 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001549 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001550 if (mPropagateBackpressure) {
1551 signalLayerUpdate();
1552 break;
1553 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001554 }
Dan Stoza50182882016-07-08 12:02:20 -07001555
Steven Thomas050b2c82017-03-06 11:45:16 -08001556 // Now that we're going to make it to the handleMessageTransaction()
1557 // call below it's safe to call updateVrFlinger(), which will
1558 // potentially trigger a display handoff.
1559 updateVrFlinger();
1560
Dan Stoza6b9454d2014-11-07 16:00:59 -08001561 bool refreshNeeded = handleMessageTransaction();
1562 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001563 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001564 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001565 // Signal a refresh if a transaction modified the window state,
1566 // a new buffer was latched, or if HWC has requested a full
1567 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001568 signalRefresh();
1569 }
1570 break;
1571 }
1572 case MessageQueue::REFRESH: {
1573 handleMessageRefresh();
1574 break;
1575 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001576 }
1577}
1578
Dan Stoza6b9454d2014-11-07 16:00:59 -08001579bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001580 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001581 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001582 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001583 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001584 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001585 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001586}
1587
Mathias Agopian4fec8732012-06-29 14:12:52 -07001588void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001589 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001590
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001591 mRefreshPending = false;
1592
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001593 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001594 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001595 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001596 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001597 for (const auto& [token, display] : mDisplays) {
1598 beginFrame(display);
1599 prepareFrame(display);
1600 doDebugFlashRegions(display, repaintEverything);
1601 doComposition(display, repaintEverything);
1602 }
1603
Adrian Roos1e1a1282017-11-01 19:05:31 +01001604 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001605 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001606
1607 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001608 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001609
Dan Stozabfbffeb2016-07-21 14:49:33 -07001610 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001611 for (const auto& [token, display] : mDisplays) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001612 mHadClientComposition =
1613 mHadClientComposition || getHwComposer().hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001614 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001615
Alec Mouri86770e52018-09-24 22:40:58 +00001616 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001617 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001618 if (mHadClientComposition) {
1619 base::unique_fd flushFence(getRenderEngine().flush());
1620 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1621 getBE().flushFence = new Fence(std::move(flushFence));
1622 } else {
1623 // Cleanup for hygiene.
1624 getBE().flushFence = Fence::NO_FENCE;
1625 }
1626 }
1627
Jorim Jaggi90535212018-05-23 23:44:06 +02001628 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001629
David Sodman7e4ae112018-02-09 15:02:28 -08001630 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001631 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001632 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001633 compositionInfo.hwc.hwcLayer = nullptr;
1634 }
David Sodmanba340492018-08-05 21:51:33 -07001635 }
David Sodman7e4ae112018-02-09 15:02:28 -08001636
1637 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001638}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001639
David Sodmanfa9b2af2017-12-24 13:28:59 -08001640
1641bool SurfaceFlinger::handleMessageInvalidate() {
1642 ATRACE_CALL();
1643 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001644}
1645
David Sodman79bba0e2018-08-05 18:07:49 -07001646void SurfaceFlinger::calculateWorkingSet() {
1647 ATRACE_CALL();
1648 ALOGV(__FUNCTION__);
1649
David Sodman79bba0e2018-08-05 18:07:49 -07001650 // build the h/w work list
1651 if (CC_UNLIKELY(mGeometryInvalid)) {
1652 mGeometryInvalid = false;
1653 for (const auto& [token, display] : mDisplays) {
1654 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001655 if (!displayId) {
1656 continue;
1657 }
David Sodman79bba0e2018-08-05 18:07:49 -07001658
Dominik Laskowski075d3172018-05-24 15:50:06 -07001659 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1660 for (size_t i = 0; i < currentLayers.size(); i++) {
1661 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001662
Dominik Laskowski075d3172018-05-24 15:50:06 -07001663 if (!layer->hasHwcLayer(*displayId)) {
1664 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1665 layer->forceClientComposition(*displayId);
1666 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001667 }
1668 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001669
1670 layer->setGeometry(display, i);
1671 if (mDebugDisableHWC || mDebugRegion) {
1672 layer->forceClientComposition(*displayId);
1673 }
David Sodman79bba0e2018-08-05 18:07:49 -07001674 }
1675 }
1676 }
1677
1678 // Set the per-frame data
1679 for (const auto& [token, display] : mDisplays) {
1680 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001681 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001682 continue;
1683 }
1684
1685 if (mDrawingState.colorMatrixChanged) {
1686 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001687 status_t result =
1688 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001689 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1690 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001691 }
1692 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1693 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001694 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001695 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1696 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1697 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001698 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001699 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1700 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1701 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001702 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001703 }
1704
Peiyong Lind3788632018-09-18 16:01:31 -07001705 // TODO(b/111562338) remove when composer 2.3 is shipped.
1706 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001707 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001708 }
1709
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001710 if (layer->getRoundedCornerState().radius > 0.0f) {
1711 layer->forceClientComposition(*displayId);
1712 }
1713
Dominik Laskowski075d3172018-05-24 15:50:06 -07001714 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001715 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001716 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001717 continue;
1718 }
1719
Dominik Laskowski075d3172018-05-24 15:50:06 -07001720 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1721 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001722 }
1723
Peiyong Lin13effd12018-07-24 17:01:47 -07001724 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001725 ColorMode colorMode;
1726 Dataspace dataSpace;
1727 RenderIntent renderIntent;
1728 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1729 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1730 }
1731 }
1732
1733 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001734
1735 for (const auto& [token, display] : mDisplays) {
1736 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001737 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001738 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001739
1740 if (displayId) {
1741 if (!layer->setHwcLayer(*displayId)) {
1742 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1743 }
1744 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001745 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001746
Dominik Laskowski05275f12018-11-01 15:03:24 -07001747 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001748 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1749 }
1750 }
David Sodman79bba0e2018-08-05 18:07:49 -07001751}
1752
David Sodmanfa9b2af2017-12-24 13:28:59 -08001753void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001754{
1755 // is debugging enabled
1756 if (CC_LIKELY(!mDebugRegion))
1757 return;
1758
David Sodmanfa9b2af2017-12-24 13:28:59 -08001759 if (display->isPoweredOn()) {
1760 // transform the dirty region into this screen's coordinate space
1761 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1762 if (!dirtyRegion.isEmpty()) {
1763 // redraw the whole screen
1764 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001765
David Sodmanfa9b2af2017-12-24 13:28:59 -08001766 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001767 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001768 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001769
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001770 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001771 }
1772 }
1773
David Sodmanfa9b2af2017-12-24 13:28:59 -08001774 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001775
1776 if (mDebugRegion > 1) {
1777 usleep(mDebugRegion * 1000);
1778 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001779
Dominik Laskowski05275f12018-11-01 15:03:24 -07001780 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001781}
1782
Adrian Roos1e1a1282017-11-01 19:05:31 +01001783void SurfaceFlinger::doTracing(const char* where) {
1784 ATRACE_CALL();
1785 ATRACE_NAME(where);
1786 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001787 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001788 }
1789}
1790
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001791void SurfaceFlinger::logLayerStats() {
1792 ATRACE_CALL();
1793 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001794 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001795 if (display->isPrimary()) {
1796 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001797 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001798 }
1799 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001800
1801 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001802 }
1803}
1804
David Sodman2b406362017-12-15 13:33:47 -08001805void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001806{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001807 ATRACE_CALL();
1808 ALOGV("preComposition");
1809
David Sodman2b406362017-12-15 13:33:47 -08001810 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1811
Mathias Agopiancd60f992012-08-16 16:28:27 -07001812 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001813 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001814 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001815 needExtraInvalidate = true;
1816 }
Robert Carr2047fae2016-11-28 14:09:09 -08001817 });
1818
Mathias Agopiancd60f992012-08-16 16:28:27 -07001819 if (needExtraInvalidate) {
1820 signalLayerUpdate();
1821 }
1822}
1823
Ana Krulece588e312018-09-18 12:32:24 -07001824void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1825 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001826 // Update queue of past composite+present times and determine the
1827 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001828 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001829 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001830 while (!getBE().mCompositePresentTimes.empty()) {
1831 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001832 // Cached values should have been updated before calling this method,
1833 // which helps avoid duplicate syscalls.
1834 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1835 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1836 break;
1837 }
1838 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001839 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001840 }
1841
1842 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001843 while (getBE().mCompositePresentTimes.size() > 16) {
1844 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001845 }
1846
Ana Krulece588e312018-09-18 12:32:24 -07001847 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001848}
1849
Ana Krulece588e312018-09-18 12:32:24 -07001850void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1851 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001852 // Integer division and modulo round toward 0 not -inf, so we need to
1853 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001854 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1855 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1856 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001857
Brian Andersond0010582017-03-07 13:20:31 -08001858 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1859 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001860 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001861 }
1862
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001863 // Snap the latency to a value that removes scheduling jitter from the
1864 // composition and present times, which often have >1ms of jitter.
1865 // Reducing jitter is important if an app attempts to extrapolate
1866 // something (such as user input) to an accurate diasplay time.
1867 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1868 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001869 nsecs_t bias = stats.vsyncPeriod / 2;
1870 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1871 nsecs_t snappedCompositeToPresentLatency =
1872 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001873
David Sodman99974d22017-11-28 12:04:33 -08001874 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001875 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1876 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001877 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001878}
1879
David Sodman2b406362017-12-15 13:33:47 -08001880void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001881{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001882 ATRACE_CALL();
1883 ALOGV("postComposition");
1884
Brian Anderson3546a3f2016-07-14 11:51:14 -07001885 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001886 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001887 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001888 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001889 }
1890
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001891 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001892 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001893
David Sodman73beded2017-11-15 11:56:06 -08001894 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001895 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001896 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001897 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001898 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001899 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001900 } else {
1901 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1902 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001903
David Sodman73beded2017-11-15 11:56:06 -08001904 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001905 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001906 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001907 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001908 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001909
Ana Krulece588e312018-09-18 12:32:24 -07001910 DisplayStatInfo stats;
1911 if (mUseScheduler) {
1912 mScheduler->getDisplayStatInfo(&stats);
1913 } else {
1914 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1915 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1916 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001917
David Sodman2b406362017-12-15 13:33:47 -08001918 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001919 // when we started doing work for this frame, but that should be okay
1920 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001921 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001922 CompositorTiming compositorTiming;
1923 {
David Sodman99974d22017-11-28 12:04:33 -08001924 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1925 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001926 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001927
Robert Carr2047fae2016-11-28 14:09:09 -08001928 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001929 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1930 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001931 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001932 recordBufferingStats(layer->getName().string(),
1933 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001934 }
Robert Carr2047fae2016-11-28 14:09:09 -08001935 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001936
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001937 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001938 if (mUseScheduler) {
1939 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001940 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001941 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1942 enableHardwareVsync();
1943 } else {
1944 disableHardwareVsync(false);
1945 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001946 }
1947 }
1948
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001949 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001950 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001951 if (mUseScheduler) {
1952 mScheduler->enableHardwareVsync();
1953 } else {
1954 enableHardwareVsync();
1955 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001956 }
1957 }
1958
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001959 if (mAnimCompositionPending) {
1960 mAnimCompositionPending = false;
1961
Brian Anderson4e606e32017-03-16 15:34:57 -07001962 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001963 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001964 std::move(presentFenceTime));
Dominik Laskowski075d3172018-05-24 15:50:06 -07001965 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001966 // The HWC doesn't support present fences, so use the refresh
1967 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001968 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001969 mAnimFrameTracker.setActualPresentTime(presentTime);
1970 }
1971 mAnimFrameTracker.advanceFrame();
1972 }
Dan Stozab90cf072015-03-05 11:05:59 -08001973
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001974 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001975 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001976 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001977 }
1978
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001979 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001980
Dominik Laskowski075d3172018-05-24 15:50:06 -07001981 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001982 return;
1983 }
1984
1985 nsecs_t currentTime = systemTime();
1986 if (mHasPoweredOff) {
1987 mHasPoweredOff = false;
1988 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001989 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001990 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001991 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1992 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001993 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001994 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001995 }
David Sodman4a36e932017-11-07 14:29:47 -08001996 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001997 }
David Sodman4a36e932017-11-07 14:29:47 -08001998 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001999
2000 {
2001 std::lock_guard lock(mTexturePoolMutex);
2002 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
2003 if (refillCount > 0) {
2004 const size_t offset = mTexturePool.size();
2005 mTexturePool.resize(mTexturePoolSize);
2006 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2007 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2008 }
2009 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002010
Marissa Wallfda30bb2018-10-12 11:34:28 -07002011 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002012 mTransactionCompletedThread.sendCallbacks();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002013}
2014
2015void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002016 ATRACE_CALL();
2017 ALOGV("rebuildLayerStacks");
2018
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002019 // We need to clear these out now as these may be holding on to a
2020 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2021 // also holds a reference. When the set of visible layers is recomputed,
2022 // some layers may be destroyed if the only thing keeping them alive was
2023 // that list of visible layers associated with each display. The layer
2024 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2025 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2026 for (const auto& [token, display] : mDisplays) {
2027 getBE().mCompositionInfo[token].clear();
2028 }
2029
Mathias Agopiancd60f992012-08-16 16:28:27 -07002030 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002031 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002032 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002033 mVisibleRegionsDirty = false;
2034 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002035
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002036 for (const auto& pair : mDisplays) {
2037 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002038 Region opaqueRegion;
2039 Region dirtyRegion;
2040 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002041 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002042 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002043 const Rect bounds = display->getBounds();
2044 if (display->isPoweredOn()) {
2045 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002046
Jeff Sharkey76488112017-02-27 14:15:18 -07002047 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002048 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002049 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002050 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002051 Region drawRegion(tr.transform(
2052 layer->visibleNonTransparentRegion));
2053 drawRegion.andSelf(bounds);
2054 if (!drawRegion.isEmpty()) {
2055 layersSortedByZ.add(layer);
2056 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002057 // Clear out the HWC layer if this layer was
2058 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002059 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002060 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002061 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002062 // WM changes display->layerStack upon sleep/awake.
2063 // Here we make sure we delete the HWC layers even if
2064 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002065 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002066 }
2067
2068 // If a layer is not going to get a release fence because
2069 // it is invisible, but it is also going to release its
2070 // old buffer, add it to the list of layers needing
2071 // fences.
2072 if (hwcLayerDestroyed) {
2073 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2074 mLayersWithQueuedFrames.cend(), layer);
2075 if (found != mLayersWithQueuedFrames.cend()) {
2076 layersNeedingFences.add(layer);
2077 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002078 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002079 });
2080 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002081 display->setVisibleLayersSortedByZ(layersSortedByZ);
2082 display->setLayersNeedingFences(layersNeedingFences);
2083 display->undefinedRegion.set(bounds);
2084 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2085 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002086 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002087 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002088}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002089
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002090// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002091// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002092// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002093// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002094// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002095// The returned HDR data space is one of
2096// - Dataspace::UNKNOWN
2097// - Dataspace::BT2020_HLG
2098// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002099Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2100 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002101 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002102 *outHdrDataSpace = Dataspace::UNKNOWN;
2103
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002104 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002105 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002106 case Dataspace::V0_SCRGB:
2107 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002108 case Dataspace::BT2020:
2109 case Dataspace::BT2020_ITU:
2110 case Dataspace::BT2020_LINEAR:
2111 case Dataspace::DISPLAY_BT2020:
2112 bestDataSpace = Dataspace::DISPLAY_BT2020;
2113 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002114 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002115 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002116 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002117 case Dataspace::BT2020_PQ:
2118 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002119 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002120 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002121 case Dataspace::BT2020_HLG:
2122 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002123 // When there's mixed PQ content and HLG content, we set the HDR
2124 // data space to be BT2020_PQ and convert HLG to PQ.
2125 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2126 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002127 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002128 break;
2129 default:
2130 break;
2131 }
Romain Guy54f154a2017-10-24 21:40:32 +01002132 }
2133
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002134 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002135}
2136
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002137// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002138void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2139 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002140 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2141 *outMode = ColorMode::NATIVE;
2142 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002143 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002144 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002145 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002146
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002147 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002148 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002149
Peiyong Lindfde5112018-06-05 10:58:41 -07002150 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002151 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002152 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002153 if (isHdr) {
2154 bestDataSpace = hdrDataSpace;
2155 }
2156
Chia-I Wu0d711262018-05-21 15:19:35 -07002157 RenderIntent intent;
2158 switch (mDisplayColorSetting) {
2159 case DisplayColorSetting::MANAGED:
2160 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002161 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002162 break;
2163 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002164 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002165 break;
2166 default: // vendor display color setting
2167 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2168 break;
2169 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002170
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002171 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002172}
2173
David Sodmanfa9b2af2017-12-24 13:28:59 -08002174void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002175{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002176 bool dirty = !display->getDirtyRegion(false).isEmpty();
2177 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2178 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002179
David Sodmanfa9b2af2017-12-24 13:28:59 -08002180 // If nothing has changed (!dirty), don't recompose.
2181 // If something changed, but we don't currently have any visible layers,
2182 // and didn't when we last did a composition, then skip it this time.
2183 // The second rule does two things:
2184 // - When all layers are removed from a display, we'll emit one black
2185 // frame, then nothing more until we get new layers.
2186 // - When a display is created with a private layer stack, we won't
2187 // emit any black frames until a layer is added to the layer stack.
2188 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002189
Dominik Laskowski075d3172018-05-24 15:50:06 -07002190 const char flagPrefix[] = {'-', '+'};
2191 static_cast<void>(flagPrefix);
2192 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2193 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2194 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002195
David Sodmanfa9b2af2017-12-24 13:28:59 -08002196 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002197
David Sodmanfa9b2af2017-12-24 13:28:59 -08002198 if (mustRecompose) {
2199 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002200 }
2201}
2202
David Sodmanfa9b2af2017-12-24 13:28:59 -08002203void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002204{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002205 if (!display->isPoweredOn()) {
2206 return;
David Sodman2b406362017-12-15 13:33:47 -08002207 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002208
Dominik Laskowski05275f12018-11-01 15:03:24 -07002209 status_t result = display->prepareFrame(getHwComposer(),
2210 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002211 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2212 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002213}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002214
David Sodmanfa9b2af2017-12-24 13:28:59 -08002215void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002216 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002217 ALOGV("doComposition");
2218
David Sodmanfa9b2af2017-12-24 13:28:59 -08002219 if (display->isPoweredOn()) {
2220 // transform the dirty region into this screen's coordinate space
2221 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002222
David Sodmanfa9b2af2017-12-24 13:28:59 -08002223 // repaint the framebuffer (if needed)
2224 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002225
David Sodmanfa9b2af2017-12-24 13:28:59 -08002226 display->dirtyRegion.clear();
2227 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002228 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002229 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002230}
2231
David Sodmanfa9b2af2017-12-24 13:28:59 -08002232void SurfaceFlinger::postFrame()
2233{
2234 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002235 const auto display = getDefaultDisplayDeviceLocked();
2236 if (display && getHwComposer().isConnected(*display->getId())) {
2237 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002238 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2239 logFrameStats();
2240 }
2241 }
2242}
2243
2244void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002245{
Mathias Agopian841cde52012-03-01 15:44:37 -08002246 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002247 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002248
David Sodmanfa9b2af2017-12-24 13:28:59 -08002249 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002250
David Sodmanfa9b2af2017-12-24 13:28:59 -08002251 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002252 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002253 if (displayId) {
2254 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002255 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002256 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002257 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002258 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002259
Chia-I Wu7b549592017-11-15 09:14:57 -08002260 // The layer buffer from the previous frame (if any) is released
2261 // by HWC only when the release fence from this frame (if any) is
2262 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002263 if (displayId && layer->hasHwcLayer(*displayId)) {
2264 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2265 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002266 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002267
2268 // If the layer was client composited in the previous frame, we
2269 // need to merge with the previous client target acquire fence.
2270 // Since we do not track that, always merge with the current
2271 // client target acquire fence when it is available, even though
2272 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002273 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002274 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002275 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002276 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002277
David Sodman15094112018-10-11 09:39:37 -07002278 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002279 }
Chia-I Wu83806892017-11-16 10:50:20 -08002280
2281 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002282 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002283 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002284 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002285 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002286 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002287 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002288 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002289 }
2290 }
2291
Dominik Laskowski075d3172018-05-24 15:50:06 -07002292 if (displayId) {
2293 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002294 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002295 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002296}
2297
Mathias Agopian87baae12012-07-31 12:38:26 -07002298void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002299{
Mathias Agopian841cde52012-03-01 15:44:37 -08002300 ATRACE_CALL();
2301
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002302 // here we keep a copy of the drawing state (that is the state that's
2303 // going to be overwritten by handleTransactionLocked()) outside of
2304 // mStateLock so that the side-effects of the State assignment
2305 // don't happen with mStateLock held (which can cause deadlocks).
2306 State drawingState(mDrawingState);
2307
Mathias Agopianca4d3602011-05-19 15:38:14 -07002308 Mutex::Autolock _l(mStateLock);
2309 const nsecs_t now = systemTime();
2310 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002311
Mathias Agopianca4d3602011-05-19 15:38:14 -07002312 // Here we're guaranteed that some transaction flags are set
2313 // so we can call handleTransactionLocked() unconditionally.
2314 // We call getTransactionFlags(), which will also clear the flags,
2315 // with mStateLock held to guarantee that mCurrentState won't change
2316 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002317
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002318 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002319 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002320 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002321
Mathias Agopianca4d3602011-05-19 15:38:14 -07002322 mLastTransactionTime = systemTime() - now;
2323 mDebugInTransaction = 0;
2324 invalidateHwcGeometry();
2325 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002326}
2327
Lloyd Piqueba04e622017-12-14 17:11:26 -08002328void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2329 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002330 const std::optional<DisplayIdentificationInfo> info =
2331 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002332
Dominik Laskowski075d3172018-05-24 15:50:06 -07002333 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002334 continue;
2335 }
2336
Lloyd Piqueba04e622017-12-14 17:11:26 -08002337 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002338 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002339 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002340 mPhysicalDisplayTokens[info->id] = new BBinder();
2341 DisplayDeviceState state;
2342 state.displayId = info->id;
2343 state.isSecure = true; // All physical displays are currently considered secure.
2344 state.displayName = info->name;
2345 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2346 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002347 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002348 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002349 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002350
Dominik Laskowski075d3172018-05-24 15:50:06 -07002351 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2352 if (index >= 0) {
2353 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2354 mInterceptor->saveDisplayDeletion(state.sequenceId);
2355 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002356 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002357 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002358 }
2359
2360 processDisplayChangesLocked();
2361 }
2362
2363 mPendingHotplugEvents.clear();
2364}
2365
Lloyd Pique99d3da52018-01-22 17:48:03 -08002366sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002367 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2368 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2369 const sp<IGraphicBufferProducer>& producer) {
2370 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002371 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002372 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002373 creationArgs.isSecure = state.isSecure;
2374 creationArgs.displaySurface = dispSurface;
2375 creationArgs.hasWideColorGamut = false;
2376 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002377
Dominik Laskowski075d3172018-05-24 15:50:06 -07002378 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2379 creationArgs.isPrimary = isInternalDisplay;
2380
2381 if (useColorManagement && displayId) {
2382 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002383 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002384 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002385 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002386 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002387
Dominik Laskowski7e045462018-05-30 13:02:02 -07002388 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002389 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002390 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002391 }
tangrobin6753a022018-08-10 10:58:54 +08002392 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002393
Dominik Laskowski075d3172018-05-24 15:50:06 -07002394 if (displayId) {
2395 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002396 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002397 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002398 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002399
Lloyd Pique90c115d2018-09-18 21:39:42 -07002400 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002401 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002402 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002403
Lloyd Pique99d3da52018-01-22 17:48:03 -08002404 // Make sure that composition can never be stalled by a virtual display
2405 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002406 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002407 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002408 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2409 }
2410
Dominik Laskowski075d3172018-05-24 15:50:06 -07002411 creationArgs.displayInstallOrientation =
2412 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002413
Lloyd Pique99d3da52018-01-22 17:48:03 -08002414 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002415 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002416
Lloyd Pique90c115d2018-09-18 21:39:42 -07002417 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002418
2419 if (maxFrameBufferAcquiredBuffers >= 3) {
2420 nativeWindowSurface->preallocateBuffers();
2421 }
2422
2423 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002424 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002425 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002426 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002427 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002428 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002429 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002430 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002431 if (!state.isVirtual()) {
2432 LOG_ALWAYS_FATAL_IF(!displayId);
2433 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002434 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002435
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002436 display->setLayerStack(state.layerStack);
2437 display->setProjection(state.orientation, state.viewport, state.frame);
2438 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002439
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002440 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002441}
2442
Lloyd Pique347200f2017-12-14 17:00:15 -08002443void SurfaceFlinger::processDisplayChangesLocked() {
2444 // here we take advantage of Vector's copy-on-write semantics to
2445 // improve performance by skipping the transaction entirely when
2446 // know that the lists are identical
2447 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2448 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2449 if (!curr.isIdenticalTo(draw)) {
2450 mVisibleRegionsDirty = true;
2451 const size_t cc = curr.size();
2452 size_t dc = draw.size();
2453
2454 // find the displays that were removed
2455 // (ie: in drawing state but not in current state)
2456 // also handle displays that changed
2457 // (ie: displays that are in both lists)
2458 for (size_t i = 0; i < dc;) {
2459 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2460 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002461 // Save display IDs before disconnecting.
2462 const auto internalDisplayId = getInternalDisplayId();
2463 const auto externalDisplayId = getExternalDisplayId();
2464
Lloyd Pique347200f2017-12-14 17:00:15 -08002465 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002466 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2467 display->disconnect(getHwComposer());
2468 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002469 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002470 if (mUseScheduler) {
2471 mScheduler->hotplugReceived(mAppConnectionHandle,
2472 EventThread::DisplayType::Primary, false);
2473 } else {
2474 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2475 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002476 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002477 if (mUseScheduler) {
2478 mScheduler->hotplugReceived(mAppConnectionHandle,
2479 EventThread::DisplayType::External, false);
2480 } else {
2481 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2482 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002483 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002484 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002485 } else {
2486 // this display is in both lists. see if something changed.
2487 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002488 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002489 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2490 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2491 if (state_binder != draw_binder) {
2492 // changing the surface is like destroying and
2493 // recreating the DisplayDevice, so we just remove it
2494 // from the drawing state, so that it get re-added
2495 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002496 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2497 display->disconnect(getHwComposer());
2498 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002499 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002500 mDrawingState.displays.removeItemsAt(i);
2501 dc--;
2502 // at this point we must loop to the next item
2503 continue;
2504 }
2505
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002506 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002507 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002508 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002509 }
2510 if ((state.orientation != draw[i].orientation) ||
2511 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002512 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002513 }
2514 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002515 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002516 }
2517 }
2518 }
2519 ++i;
2520 }
2521
2522 // find displays that were added
2523 // (ie: in current state but not in drawing state)
2524 for (size_t i = 0; i < cc; i++) {
2525 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2526 const DisplayDeviceState& state(curr[i]);
2527
2528 sp<DisplaySurface> dispSurface;
2529 sp<IGraphicBufferProducer> producer;
2530 sp<IGraphicBufferProducer> bqProducer;
2531 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002532 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002533
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002535 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002536 // Virtual displays without a surface are dormant:
2537 // they have external state (layer stack, projection,
2538 // etc.) but no internal state (i.e. a DisplayDevice).
2539 if (state.surface != nullptr) {
2540 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002541 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002542 int width = 0;
2543 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2544 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2545 int height = 0;
2546 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2547 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2548 int intFormat = 0;
2549 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2550 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002551 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002552
Dominik Laskowski075d3172018-05-24 15:50:06 -07002553 displayId =
2554 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002555 }
2556
2557 // TODO: Plumb requested format back up to consumer
2558
2559 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002560 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002561 bqProducer, bqConsumer,
2562 state.displayName);
2563
2564 dispSurface = vds;
2565 producer = vds;
2566 }
2567 } else {
2568 ALOGE_IF(state.surface != nullptr,
2569 "adding a supported display, but rendering "
2570 "surface is provided (%p), ignoring it",
2571 state.surface.get());
2572
Dominik Laskowski075d3172018-05-24 15:50:06 -07002573 displayId = state.displayId;
2574 LOG_ALWAYS_FATAL_IF(!displayId);
2575 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002576 producer = bqProducer;
2577 }
2578
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002579 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002580 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002581 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002582 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002583 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002584 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002585 LOG_ALWAYS_FATAL_IF(!displayId);
2586
2587 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002588 if (mUseScheduler) {
2589 mScheduler->hotplugReceived(mAppConnectionHandle,
2590 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002591 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002592 } else {
2593 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2594 true);
2595 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002596 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002597 if (mUseScheduler) {
2598 mScheduler->hotplugReceived(mAppConnectionHandle,
2599 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002600 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002601 } else {
2602 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2603 true);
2604 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002605 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002606 }
2607 }
2608 }
2609 }
2610 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002611
2612 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002613}
2614
Mathias Agopian87baae12012-07-31 12:38:26 -07002615void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002616{
Dan Stoza7dde5992015-05-22 09:51:44 -07002617 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002618 mCurrentState.traverseInZOrder([](Layer* layer) {
2619 layer->notifyAvailableFrames();
2620 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002621
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622 /*
2623 * Traversal of the children
2624 * (perform the transaction for each of them if needed)
2625 */
2626
Robert Carr720e5062018-07-30 17:45:14 -07002627 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002628 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002629 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002630 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002631 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632
2633 const uint32_t flags = layer->doTransaction(0);
2634 if (flags & Layer::eVisibleRegion)
2635 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002636
2637 if (flags & Layer::eInputInfoChanged) {
2638 inputChanged = true;
2639 }
Robert Carr2047fae2016-11-28 14:09:09 -08002640 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002641 }
2642
2643 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002644 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645 */
2646
Mathias Agopiane57f2922012-08-09 16:29:12 -07002647 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002648 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002649 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002650 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002652 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002653 // The transform hint might have changed for some layers
2654 // (either because a display has changed, or because a layer
2655 // as changed).
2656 //
2657 // Walk through all the layers in currentLayers,
2658 // and update their transform hint.
2659 //
2660 // If a layer is visible only on a single display, then that
2661 // display is used to calculate the hint, otherwise we use the
2662 // default display.
2663 //
2664 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2665 // the hint is set before we acquire a buffer from the surface texture.
2666 //
2667 // NOTE: layer transactions have taken place already, so we use their
2668 // drawing state. However, SurfaceFlinger's own transaction has not
2669 // happened yet, so we must use the current state layer list
2670 // (soon to become the drawing state list).
2671 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002672 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002673 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002674 bool first = true;
2675 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002676 // NOTE: we rely on the fact that layers are sorted by
2677 // layerStack first (so we don't have to traverse the list
2678 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002679 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002680 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002681 currentlayerStack = layerStack;
2682 // figure out if this layerstack is mirrored
2683 // (more than one display) if so, pick the default display,
2684 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002685 hintDisplay = nullptr;
2686 for (const auto& [token, display] : mDisplays) {
2687 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2688 if (hintDisplay) {
2689 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002690 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002691 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002692 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002693 }
2694 }
2695 }
2696 }
Chet Haase91d25932013-04-11 15:24:55 -07002697
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002698 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002699 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2700 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002701
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002702 // could be null when this layer is using a layerStack
2703 // that is not visible on any display. Also can occur at
2704 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002705 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002706 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002707
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002708 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002709 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002710 if (hintDisplay) {
2711 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002712 }
Robert Carr2047fae2016-11-28 14:09:09 -08002713
2714 first = false;
2715 });
Mathias Agopian84300952012-11-21 16:02:13 -08002716 }
2717
2718
Mathias Agopian3559b072012-08-15 13:46:03 -07002719 /*
2720 * Perform our own transaction if needed
2721 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002722
2723 if (mLayersAdded) {
2724 mLayersAdded = false;
2725 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002726 mVisibleRegionsDirty = true;
2727 }
2728
2729 // some layers might have been removed, so
2730 // we need to update the regions they're exposing.
2731 if (mLayersRemoved) {
2732 mLayersRemoved = false;
2733 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002734 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002735 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002736 // this layer is not visible anymore
2737 // TODO: we could traverse the tree from front to back and
2738 // compute the actual visible region
2739 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002740 Region visibleReg;
2741 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002742 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002743 }
Robert Carr2047fae2016-11-28 14:09:09 -08002744 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745 }
2746
2747 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002748
Vishnu Nairde19f852018-12-18 16:11:53 -08002749 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002750 updateInputWindows();
2751 }
2752
Riley Andrews03414a12014-07-01 14:22:59 -07002753 updateCursorAsync();
2754}
2755
Robert Carr720e5062018-07-30 17:45:14 -07002756void SurfaceFlinger::updateInputWindows() {
2757 ATRACE_CALL();
2758
Vishnu Nairde19f852018-12-18 16:11:53 -08002759 if (mInputFlinger == nullptr) {
2760 return;
2761 }
2762
Robert Carr720e5062018-07-30 17:45:14 -07002763 Vector<InputWindowInfo> inputHandles;
2764
2765 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2766 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002767 // When calculating the screen bounds we ignore the transparent region since it may
2768 // result in an unwanted offset.
2769 inputHandles.add(layer->fillInputInfo(
2770 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002771 }
2772 });
2773 mInputFlinger->setInputWindows(inputHandles);
2774}
2775
Riley Andrews03414a12014-07-01 14:22:59 -07002776void SurfaceFlinger::updateCursorAsync()
2777{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002778 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002779 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002780 continue;
2781 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002782
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002783 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2784 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002785 }
2786 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002787}
2788
chaviw61626f22018-11-15 16:26:27 -08002789void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2790 if (layer->hasReadyFrame()) {
2791 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2792 if (layer->shouldPresentNow(expectedPresentTime)) {
2793 bool ignored = false;
2794 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2795 }
2796 }
2797 layer->releasePendingBuffer(systemTime());
2798}
2799
Mathias Agopian4fec8732012-06-29 14:12:52 -07002800void SurfaceFlinger::commitTransaction()
2801{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002802 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002803 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002804 for (const auto& l : mLayersPendingRemoval) {
2805 recordBufferingStats(l->getName().string(),
2806 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002807
2808 // We need to release the HWC layers when the Layer is removed
2809 // from the current state otherwise the HWC layer just continues
2810 // showing at its last configured state until we eventually
2811 // abandon the buffer queue.
2812 if (l->isRemovedFromCurrentState()) {
Robert Carr3aee9892018-11-07 12:53:41 -08002813 l->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* child) {
chaviw61626f22018-11-15 16:26:27 -08002814 child->destroyHwcLayersForAllDisplays();
2815 latchAndReleaseBuffer(child);
Robert Carr3aee9892018-11-07 12:53:41 -08002816 });
Robert Carr2e102c92018-10-23 12:11:15 -07002817 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002818 }
2819 mLayersPendingRemoval.clear();
2820 }
2821
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002822 // If this transaction is part of a window animation then the next frame
2823 // we composite should be considered an animation as well.
2824 mAnimCompositionPending = mAnimTransactionPending;
2825
Mathias Agopian4fec8732012-06-29 14:12:52 -07002826 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002827 // clear the "changed" flags in current state
2828 mCurrentState.colorMatrixChanged = false;
2829
Robert Carr1f0a16a2016-10-24 16:27:39 -07002830 mDrawingState.traverseInZOrder([](Layer* layer) {
2831 layer->commitChildList();
2832 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002833 mTransactionPending = false;
2834 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002835 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002836}
2837
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002838void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2839 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002840 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002841 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002842
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843 Region aboveOpaqueLayers;
2844 Region aboveCoveredLayers;
2845 Region dirty;
2846
Mathias Agopian87baae12012-07-31 12:38:26 -07002847 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848
Robert Carr2047fae2016-11-28 14:09:09 -08002849 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Jesse Hall01e29052013-02-19 16:13:35 -08002850 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002851 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002852 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002853 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002854
Mathias Agopianab028732010-03-16 16:41:46 -07002855 /*
2856 * opaqueRegion: area of a surface that is fully opaque.
2857 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002859
2860 /*
2861 * visibleRegion: area of a surface that is visible on screen
2862 * and not fully transparent. This is essentially the layer's
2863 * footprint minus the opaque regions above it.
2864 * Areas covered by a translucent surface are considered visible.
2865 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002867
2868 /*
2869 * coveredRegion: area of a surface that is covered by all
2870 * visible regions above it (which includes the translucent areas).
2871 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002873
Jesse Halla8026d22012-09-25 13:25:04 -07002874 /*
2875 * transparentRegion: area of a surface that is hinted to be completely
2876 * transparent. This is only used to tell when the layer has no visible
2877 * non-transparent regions and can be removed from the layer list. It
2878 * does not affect the visibleRegion of this layer or any layers
2879 * beneath it. The hint may not be correct if apps don't respect the
2880 * SurfaceView restrictions (which, sadly, some don't).
2881 */
2882 Region transparentRegion;
2883
Mathias Agopianab028732010-03-16 16:41:46 -07002884
2885 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002886 if (CC_LIKELY(layer->isVisible())) {
Ady Abraham83729882018-12-07 12:26:48 -08002887 const bool translucent = !layer->isDrawingOpaque();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002888 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07002889
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002891 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002892 if (!visibleRegion.isEmpty()) {
2893 // Remove the transparent area from the visible region
2894 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002895 if (tr.preserveRects()) {
2896 // transform the transparent region
Ady Abraham83729882018-12-07 12:26:48 -08002897 transparentRegion =
2898 tr.transform(layer->getDrawingActiveTransparentRegion());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002899 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002900 // transformation too complex, can't do the
2901 // transparent region optimization.
2902 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002903 }
Mathias Agopianab028732010-03-16 16:41:46 -07002904 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002905
Mathias Agopianab028732010-03-16 16:41:46 -07002906 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002907 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002908 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002909 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002910 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002911 // the opaque region is the layer's footprint
2912 opaqueRegion = visibleRegion;
2913 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002914 }
2915 }
2916
Robert Carre5f4f692018-01-12 13:12:28 -08002917 if (visibleRegion.isEmpty()) {
2918 layer->clearVisibilityRegions();
2919 return;
2920 }
2921
Mathias Agopianab028732010-03-16 16:41:46 -07002922 // Clip the covered region to the visible region
2923 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2924
2925 // Update aboveCoveredLayers for next (lower) layer
2926 aboveCoveredLayers.orSelf(visibleRegion);
2927
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002928 // subtract the opaque region covered by the layers above us
2929 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930
2931 // compute this layer's dirty region
2932 if (layer->contentDirty) {
2933 // we need to invalidate the whole region
2934 dirty = visibleRegion;
2935 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002936 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937 layer->contentDirty = false;
2938 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002939 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002940 * the exposed region consists of two components:
2941 * 1) what's VISIBLE now and was COVERED before
2942 * 2) what's EXPOSED now less what was EXPOSED before
2943 *
2944 * note that (1) is conservative, we start with the whole
2945 * visible region but only keep what used to be covered by
2946 * something -- which mean it may have been exposed.
2947 *
2948 * (2) handles areas that were not covered by anything but got
2949 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002950 */
Mathias Agopianab028732010-03-16 16:41:46 -07002951 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002952 const Region oldVisibleRegion = layer->visibleRegion;
2953 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002954 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2955 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956 }
2957 dirty.subtractSelf(aboveOpaqueLayers);
2958
2959 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002960 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002961
Mathias Agopianab028732010-03-16 16:41:46 -07002962 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002963 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002964
Jesse Halla8026d22012-09-25 13:25:04 -07002965 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002966 layer->setVisibleRegion(visibleRegion);
2967 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002968 layer->setVisibleNonTransparentRegion(
2969 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002970 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002971
Mathias Agopian87baae12012-07-31 12:38:26 -07002972 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002973}
2974
Chia-I Wuab0c3192017-08-01 11:29:00 -07002975void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002976 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002977 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2978 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002979 }
2980 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002981}
2982
Dan Stoza6b9454d2014-11-07 16:00:59 -08002983bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002984{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002985 ALOGV("handlePageFlip");
2986
Brian Andersond6927fb2016-07-23 23:37:30 -07002987 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002988
Mathias Agopian4fec8732012-06-29 14:12:52 -07002989 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002990 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002991 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002992
2993 // Store the set of layers that need updates. This set must not change as
2994 // buffers are being latched, as this could result in a deadlock.
2995 // Example: Two producers share the same command stream and:
2996 // 1.) Layer 0 is latched
2997 // 2.) Layer 0 gets a new frame
2998 // 2.) Layer 1 gets a new frame
2999 // 3.) Layer 1 is latched.
3000 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3001 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003002 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003003 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003004 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003005 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3006 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003007 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003008 } else {
3009 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003010 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003011 } else {
3012 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003013 }
Robert Carr2047fae2016-11-28 14:09:09 -08003014 });
3015
Dan Stoza9e56aa02015-11-02 13:00:03 -08003016 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00003017 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07003018 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003019 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003020 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003021 newDataLatched = true;
3022 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003023 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003024
Alec Mouri86770e52018-09-24 22:40:58 +00003025 // Clear the renderengine fence here...
3026 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3027 // clear instead of sp::clear.
3028 getBE().flushFence = Fence::NO_FENCE;
3029
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003030 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003031
Vishnu Nairde19f852018-12-18 16:11:53 -08003032 if (visibleRegions) {
3033 // Update input window info if the layer receives its first buffer.
3034 updateInputWindows();
3035 }
3036
Dan Stoza6b9454d2014-11-07 16:00:59 -08003037 // If we will need to wake up at some time in the future to deal with a
3038 // queued frame that shouldn't be displayed during this vsync period, wake
3039 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003040 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003041 signalLayerUpdate();
3042 }
3043
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003044 // enter boot animation on first buffer latch
3045 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3046 ALOGI("Enter boot animation");
3047 mBootStage = BootStage::BOOTANIMATION;
3048 }
3049
Dan Stoza6b9454d2014-11-07 16:00:59 -08003050 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003051 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003052}
3053
Mathias Agopianad456f92011-01-13 17:53:01 -08003054void SurfaceFlinger::invalidateHwcGeometry()
3055{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003056 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003057}
3058
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003059void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003060 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003061 // We only need to actually compose the display if:
3062 // 1) It is being handled by hardware composer, which may need this to
3063 // keep its virtual display state machine in sync, or
3064 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003065 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003066 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003067 return;
3068 }
3069
Dan Stoza9e56aa02015-11-02 13:00:03 -08003070 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003071 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003072
3073 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003074 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075}
3076
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003077bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003078 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003079
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003080 const Region bounds(display->bounds());
3081 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003082 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07003083 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003084 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003085
Peiyong Lind3788632018-09-18 16:01:31 -07003086 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003087 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003088
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003089 // Framebuffer will live in this scope for GPU composition.
3090 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3091
Dan Stoza9e56aa02015-11-02 13:00:03 -08003092 if (hasClientComposition) {
3093 ALOGV("hasClientComposition");
3094
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003095 sp<GraphicBuffer> buf = display->dequeueBuffer();
3096
3097 if (buf == nullptr) {
3098 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3099 "client composition for this frame",
3100 display->getDisplayName().c_str());
3101 return false;
3102 }
3103
3104 // Bind the framebuffer in this scope.
3105 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3106 buf->getNativeBuffer());
3107
3108 if (fbo->getStatus() != NO_ERROR) {
3109 ALOGW("Binding buffer for display [%s] failed with status: %d",
3110 display->getDisplayName().c_str(), fbo->getStatus());
3111 return false;
3112 }
3113
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003114 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003115 if (display->hasWideColorGamut()) {
3116 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003117 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003118 getRenderEngine().setOutputDataSpace(outputDataspace);
3119 getRenderEngine().setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003120 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003121
Lloyd Pique441d5042018-10-18 16:49:51 -07003122 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003123 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003124 getHwComposer()
3125 .hasDisplayCapability(displayId,
3126 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003127
Peiyong Lind3788632018-09-18 16:01:31 -07003128 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003129 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3130 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003131 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003132 }
3133
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003134 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003135
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003136 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003137 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003138 // when using overlays, we assume a fully transparent framebuffer
3139 // NOTE: we could reduce how much we need to clear, for instance
3140 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003141 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003142 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003143 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003144 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003145 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003146 // we're left with the letterbox region
3147 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003148 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003149
3150 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003151 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003152
Mathias Agopianb9494d52012-04-18 02:28:45 -07003153 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003154 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003155 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003156 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003157 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003158 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003159
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003160 const Rect& bounds = display->getBounds();
3161 const Rect& scissor = display->getScissor();
3162 if (scissor != bounds) {
3163 // scissor doesn't match the screen's dimensions, so we
3164 // need to clear everything outside of it and enable
3165 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003166
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003167 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003168 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003169 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003170 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003171
Mathias Agopian85d751c2012-08-29 16:59:24 -07003172 /*
3173 * and then, render the layers targeted at the framebuffer
3174 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003175
Dan Stoza9e56aa02015-11-02 13:00:03 -08003176 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003177 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003178 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003179 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003180 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003181 displayTransform.transform(layer->visibleRegion)));
3182 ALOGV("Layer: %s", layer->getName().string());
3183 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003184 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003185 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003186 case HWC2::Composition::Cursor:
3187 case HWC2::Composition::Device:
3188 case HWC2::Composition::Sideband:
3189 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003190 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003191 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Ady Abraham83729882018-12-07 12:26:48 -08003192 layer->isDrawingOpaque() && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003193 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003194 // never clear the very first layer since we're
3195 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003196 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003197 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003198 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003199 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003200 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003201 if (layer->hasColorTransform()) {
3202 mat4 tmpMatrix;
3203 if (applyColorMatrix) {
3204 tmpMatrix = mDrawingState.colorMatrix;
3205 }
3206 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003207 getRenderEngine().setColorTransform(tmpMatrix);
3208 } else {
3209 getRenderEngine().setColorTransform(colorMatrix);
3210 }
David Sodmanc1498e62018-09-12 14:36:26 -07003211 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003212 break;
3213 }
3214 default:
3215 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003216 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003217 } else {
3218 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003219 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003220 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003221 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003222
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003223 // Perform some cleanup steps if we used client composition.
3224 if (hasClientComposition) {
3225 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003226 getRenderEngine().disableScissor();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003227 display->finishBuffer();
3228 // Clear out error flags here so that we don't wait until next
3229 // composition to log.
3230 getRenderEngine().checkErrors();
3231 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003232 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233}
3234
Chia-I Wu28e3a252018-09-07 12:05:02 -07003235void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003236 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003237 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238}
3239
Dan Stoza7d89d062015-04-30 13:29:25 -07003240status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003241 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003242 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003243 const sp<Layer>& lbc,
3244 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003245{
Dan Stoza7d89d062015-04-30 13:29:25 -07003246 // add this layer to the current state list
3247 {
3248 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003249 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003250 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3251 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003252 return NO_MEMORY;
3253 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003254 if (parent == nullptr) {
3255 mCurrentState.layersSortedByZ.add(lbc);
3256 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003257 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003258 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003259 lbc->onRemovedFromCurrentState();
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003260 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003261 parent->addChild(lbc);
3262 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003263
Yiwei Zhang243b3782018-05-15 17:40:04 -07003264 if (gbc != nullptr) {
3265 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3266 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3267 mMaxGraphicBufferProducerListSize,
3268 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3269 mGraphicBufferProducerList.size(),
3270 mMaxGraphicBufferProducerListSize, mNumLayers);
3271 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003272 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003273 }
3274
Mathias Agopian96f08192010-06-02 23:28:45 -07003275 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003276 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003277
Dan Stoza7d89d062015-04-30 13:29:25 -07003278 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003279}
3280
Robert Carr8d2711b2018-11-14 16:36:18 -08003281status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003282 Mutex::Autolock _l(mStateLock);
Robert Carr8d2711b2018-11-14 16:36:18 -08003283 return removeLayerLocked(mStateLock, layer);
chaviwca27f252018-02-06 16:46:39 -08003284}
Robert Carr7f9b8992017-03-10 11:08:39 -08003285
Robert Carr8d2711b2018-11-14 16:36:18 -08003286status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer) {
chaviw5aedec92018-10-22 10:40:38 -07003287 if (layer->isLayerDetached()) {
3288 return NO_ERROR;
3289 }
3290
Robert Carr1f0a16a2016-10-24 16:27:39 -07003291 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003292 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003293 if (p != nullptr) {
Chia-I Wufae51c42017-06-15 12:53:59 -07003294 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003295 } else {
3296 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003297 }
3298
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003299 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003300
3301 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003302 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003303}
3304
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003305uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003306 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003307}
3308
Mathias Agopian3f844832013-08-07 21:24:32 -07003309uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003310 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003311}
3312
Mathias Agopian3f844832013-08-07 21:24:32 -07003313uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003314 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003315}
3316
3317uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003318 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003319 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003320 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003321 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003322 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003323 }
3324 return old;
3325}
3326
chaviwca27f252018-02-06 16:46:39 -08003327bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3328 for (const ComposerState& state : states) {
3329 // Here we need to check that the interface we're given is indeed
3330 // one of our own. A malicious client could give us a nullptr
3331 // IInterface, or one of its own or even one of our own but a
3332 // different type. All these situations would cause us to crash.
3333 if (state.client == nullptr) {
3334 return true;
3335 }
3336
3337 sp<IBinder> binder = IInterface::asBinder(state.client);
3338 if (binder == nullptr) {
3339 return true;
3340 }
3341
3342 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3343 return true;
3344 }
3345 }
3346 return false;
3347}
3348
Mathias Agopian8b33f032012-07-24 20:43:54 -07003349void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003350 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003351 const Vector<DisplayState>& displays,
3352 uint32_t flags)
3353{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003354 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003355 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003356 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003357
chaviwca27f252018-02-06 16:46:39 -08003358 if (containsAnyInvalidClientState(states)) {
3359 return;
3360 }
3361
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003362 if (flags & eAnimation) {
3363 // For window updates that are part of an animation we must wait for
3364 // previous animation "frames" to be handled.
3365 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003366 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003367 if (CC_UNLIKELY(err != NO_ERROR)) {
3368 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003369 // caller after a few seconds.
3370 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3371 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003372 mAnimTransactionPending = false;
3373 break;
3374 }
3375 }
3376 }
3377
chaviwca27f252018-02-06 16:46:39 -08003378 for (const DisplayState& display : displays) {
3379 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003380 }
3381
Marissa Walle2ffb422018-10-12 11:33:52 -07003382 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003383 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003384 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003385 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003386 // If the state doesn't require a traversal and there are callbacks, send them now
3387 if (!(clientStateFlags & eTraversalNeeded)) {
3388 mTransactionCompletedThread.sendCallbacks();
3389 }
3390 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003391
3392 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3393 // as destroyed should only occur after setting all other states. This is to allow for a
3394 // child re-parent to happen before marking its original parent as destroyed (which would
3395 // then mark the child as destroyed).
3396 for (const ComposerState& state : states) {
3397 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003398 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003399
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003400 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3401 // anyway. This can be used as a flush mechanism for previous async transactions.
3402 // Empty animation transaction can be used to simulate back-pressure, so also force a
3403 // transaction for empty animation transactions.
3404 if (transactionFlags == 0 &&
3405 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003406 transactionFlags = eTransactionNeeded;
3407 }
3408
Mathias Agopian386aa982011-11-07 21:58:03 -08003409 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003410 if (mInterceptor->isEnabled()) {
3411 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003412 }
Irvel468051e2016-06-13 16:44:44 -07003413
Mathias Agopian386aa982011-11-07 21:58:03 -08003414 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003415 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3416 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003417 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003418
3419 // if this is a synchronous transaction, wait for it to take effect
3420 // before returning.
3421 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003422 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003423 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003424 if (flags & eAnimation) {
3425 mAnimTransactionPending = true;
3426 }
3427 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003428 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3429 if (CC_UNLIKELY(err != NO_ERROR)) {
3430 // just in case something goes wrong in SF, return to the
3431 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003432 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3433 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003434 break;
3435 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003436 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003437 }
3438}
3439
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003440uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3441 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3442 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003443
Mathias Agopiane57f2922012-08-09 16:29:12 -07003444 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003445 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3446
3447 const uint32_t what = s.what;
3448 if (what & DisplayState::eSurfaceChanged) {
3449 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3450 state.surface = s.surface;
3451 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003452 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003453 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003454 if (what & DisplayState::eLayerStackChanged) {
3455 if (state.layerStack != s.layerStack) {
3456 state.layerStack = s.layerStack;
3457 flags |= eDisplayTransactionNeeded;
3458 }
3459 }
3460 if (what & DisplayState::eDisplayProjectionChanged) {
3461 if (state.orientation != s.orientation) {
3462 state.orientation = s.orientation;
3463 flags |= eDisplayTransactionNeeded;
3464 }
3465 if (state.frame != s.frame) {
3466 state.frame = s.frame;
3467 flags |= eDisplayTransactionNeeded;
3468 }
3469 if (state.viewport != s.viewport) {
3470 state.viewport = s.viewport;
3471 flags |= eDisplayTransactionNeeded;
3472 }
3473 }
3474 if (what & DisplayState::eDisplaySizeChanged) {
3475 if (state.width != s.width) {
3476 state.width = s.width;
3477 flags |= eDisplayTransactionNeeded;
3478 }
3479 if (state.height != s.height) {
3480 state.height = s.height;
3481 flags |= eDisplayTransactionNeeded;
3482 }
3483 }
3484
Mathias Agopiane57f2922012-08-09 16:29:12 -07003485 return flags;
3486}
3487
Robert Carrd4ae7f32018-06-07 16:10:57 -07003488bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3489 IPCThreadState* ipc = IPCThreadState::self();
3490 const int pid = ipc->getCallingPid();
3491 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003492 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003493 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003494 return false;
3495 }
3496 return true;
3497}
3498
chaviwca27f252018-02-06 16:46:39 -08003499uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3500 const layer_state_t& s = composerState.state;
3501 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3502
Mathias Agopian13127d82013-03-05 17:47:11 -08003503 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003504 if (layer == nullptr) {
3505 return 0;
3506 }
3507
chaviw8b3871a2017-11-01 17:41:01 -07003508 uint32_t flags = 0;
3509
Garfield Tan8a3083e2018-12-03 13:21:07 -08003510 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003511 bool geometryAppliesWithResize =
3512 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003513
3514 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3515 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003516 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003517 layer->pushPendingState();
3518 }
3519
chaviw8b3871a2017-11-01 17:41:01 -07003520 if (what & layer_state_t::ePositionChanged) {
3521 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3522 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003523 }
chaviw8b3871a2017-11-01 17:41:01 -07003524 }
3525 if (what & layer_state_t::eLayerChanged) {
3526 // NOTE: index needs to be calculated before we update the state
3527 const auto& p = layer->getParent();
3528 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003529 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003530 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003531 mCurrentState.layersSortedByZ.removeAt(idx);
3532 mCurrentState.layersSortedByZ.add(layer);
3533 // we need traversal (state changed)
3534 // AND transaction (list changed)
3535 flags |= eTransactionNeeded|eTraversalNeeded;
3536 }
chaviw8b3871a2017-11-01 17:41:01 -07003537 } else {
3538 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003539 flags |= eTransactionNeeded|eTraversalNeeded;
3540 }
3541 }
chaviw8b3871a2017-11-01 17:41:01 -07003542 }
3543 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003544 // NOTE: index needs to be calculated before we update the state
3545 const auto& p = layer->getParent();
3546 if (p == nullptr) {
3547 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3548 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3549 mCurrentState.layersSortedByZ.removeAt(idx);
3550 mCurrentState.layersSortedByZ.add(layer);
3551 // we need traversal (state changed)
3552 // AND transaction (list changed)
3553 flags |= eTransactionNeeded|eTraversalNeeded;
3554 }
3555 } else {
3556 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3557 flags |= eTransactionNeeded|eTraversalNeeded;
3558 }
chaviw8b3871a2017-11-01 17:41:01 -07003559 }
3560 }
3561 if (what & layer_state_t::eSizeChanged) {
3562 if (layer->setSize(s.w, s.h)) {
3563 flags |= eTraversalNeeded;
3564 }
3565 }
3566 if (what & layer_state_t::eAlphaChanged) {
3567 if (layer->setAlpha(s.alpha))
3568 flags |= eTraversalNeeded;
3569 }
3570 if (what & layer_state_t::eColorChanged) {
3571 if (layer->setColor(s.color))
3572 flags |= eTraversalNeeded;
3573 }
Peiyong Lind3788632018-09-18 16:01:31 -07003574 if (what & layer_state_t::eColorTransformChanged) {
3575 if (layer->setColorTransform(s.colorTransform)) {
3576 flags |= eTraversalNeeded;
3577 }
3578 }
chaviw8b3871a2017-11-01 17:41:01 -07003579 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003580 // TODO: b/109894387
3581 //
3582 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3583 // rotation. To see the problem observe that if we have a square parent, and a child
3584 // of the same size, then we rotate the child 45 degrees around it's center, the child
3585 // must now be cropped to a non rectangular 8 sided region.
3586 //
3587 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3588 // private API, and the WindowManager only uses rotation in one case, which is on a top
3589 // level layer in which cropping is not an issue.
3590 //
3591 // However given that abuse of rotation matrices could lead to surfaces extending outside
3592 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3593 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3594 // transformations.
3595 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003596 flags |= eTraversalNeeded;
3597 }
3598 if (what & layer_state_t::eTransparentRegionChanged) {
3599 if (layer->setTransparentRegionHint(s.transparentRegion))
3600 flags |= eTraversalNeeded;
3601 }
3602 if (what & layer_state_t::eFlagsChanged) {
3603 if (layer->setFlags(s.flags, s.mask))
3604 flags |= eTraversalNeeded;
3605 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003606 if (what & layer_state_t::eCropChanged_legacy) {
3607 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003608 flags |= eTraversalNeeded;
3609 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003610 if (what & layer_state_t::eCornerRadiusChanged) {
3611 if (layer->setCornerRadius(s.cornerRadius))
3612 flags |= eTraversalNeeded;
3613 }
chaviw8b3871a2017-11-01 17:41:01 -07003614 if (what & layer_state_t::eLayerStackChanged) {
3615 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3616 // We only allow setting layer stacks for top level layers,
3617 // everything else inherits layer stack from its parent.
3618 if (layer->hasParent()) {
3619 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3620 layer->getName().string());
3621 } else if (idx < 0) {
3622 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3623 "that also does not appear in the top level layer list. Something"
3624 " has gone wrong.", layer->getName().string());
3625 } else if (layer->setLayerStack(s.layerStack)) {
3626 mCurrentState.layersSortedByZ.removeAt(idx);
3627 mCurrentState.layersSortedByZ.add(layer);
3628 // we need traversal (state changed)
3629 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003630 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003631 }
3632 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003633 if (what & layer_state_t::eDeferTransaction_legacy) {
3634 if (s.barrierHandle_legacy != nullptr) {
3635 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3636 } else if (s.barrierGbp_legacy != nullptr) {
3637 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003638 if (authenticateSurfaceTextureLocked(gbp)) {
3639 const auto& otherLayer =
3640 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003641 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003642 } else {
3643 ALOGE("Attempt to defer transaction to to an"
3644 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003645 }
3646 }
chaviw8b3871a2017-11-01 17:41:01 -07003647 // We don't trigger a traversal here because if no other state is
3648 // changed, we don't want this to cause any more work
3649 }
3650 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003651 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003652 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003653 if (!hadParent) {
3654 mCurrentState.layersSortedByZ.remove(layer);
3655 }
chaviw8b3871a2017-11-01 17:41:01 -07003656 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003657 }
chaviw8b3871a2017-11-01 17:41:01 -07003658 }
3659 if (what & layer_state_t::eReparentChildren) {
3660 if (layer->reparentChildren(s.reparentHandle)) {
3661 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003662 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003663 }
chaviw8b3871a2017-11-01 17:41:01 -07003664 if (what & layer_state_t::eDetachChildren) {
3665 layer->detachChildren();
3666 }
3667 if (what & layer_state_t::eOverrideScalingModeChanged) {
3668 layer->setOverrideScalingMode(s.overrideScalingMode);
3669 // We don't trigger a traversal here because if no other state is
3670 // changed, we don't want this to cause any more work
3671 }
Marissa Wall61c58622018-07-18 10:12:20 -07003672 if (what & layer_state_t::eTransformChanged) {
3673 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3674 }
3675 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3676 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3677 flags |= eTraversalNeeded;
3678 }
3679 if (what & layer_state_t::eCropChanged) {
3680 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3681 }
Marissa Wall861616d2018-10-22 12:52:23 -07003682 if (what & layer_state_t::eFrameChanged) {
3683 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3684 }
Marissa Wall61c58622018-07-18 10:12:20 -07003685 if (what & layer_state_t::eBufferChanged) {
3686 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3687 }
3688 if (what & layer_state_t::eAcquireFenceChanged) {
3689 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3690 }
3691 if (what & layer_state_t::eDataspaceChanged) {
3692 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3693 }
3694 if (what & layer_state_t::eHdrMetadataChanged) {
3695 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3696 }
3697 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3698 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3699 }
3700 if (what & layer_state_t::eApiChanged) {
3701 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3702 }
3703 if (what & layer_state_t::eSidebandStreamChanged) {
3704 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3705 }
Robert Carr720e5062018-07-30 17:45:14 -07003706 if (what & layer_state_t::eInputInfoChanged) {
3707 layer->setInputInfo(s.inputInfo);
3708 flags |= eTraversalNeeded;
3709 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003710 std::vector<sp<CallbackHandle>> callbackHandles;
3711 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3712 mTransactionCompletedThread.run();
3713 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3714 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3715 }
3716 }
3717 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3718 // Do not put anything that updates layer state or modifies flags after
3719 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003720 return flags;
3721}
3722
chaviwca27f252018-02-06 16:46:39 -08003723void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3724 const layer_state_t& state = composerState.state;
3725 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3726
3727 sp<Layer> layer(client->getLayerUser(state.surface));
3728 if (layer == nullptr) {
3729 return;
3730 }
3731
chaviwca27f252018-02-06 16:46:39 -08003732 if (state.what & layer_state_t::eDestroySurface) {
3733 removeLayerLocked(mStateLock, layer);
3734 }
3735}
3736
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003737status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003738 const String8& name,
3739 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003740 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003741 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003742 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003743{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003744 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003745 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003746 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003747 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003748 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003749
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003750 status_t result = NO_ERROR;
3751
3752 sp<Layer> layer;
3753
Cody Northropbc755282017-03-31 12:00:08 -06003754 String8 uniqueName = getUniqueLayerName(name);
3755
Mathias Agopian3165cc22012-08-08 19:42:09 -07003756 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003757 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003758 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3759 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003760
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003761 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003762 case ISurfaceComposerClient::eFXSurfaceBufferState:
3763 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3764 break;
chaviw13fdc492017-06-27 12:40:18 -07003765 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003766 // check if buffer size is set for color layer.
3767 if (w > 0 || h > 0) {
3768 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3769 int(w), int(h));
3770 return BAD_VALUE;
3771 }
3772
chaviw13fdc492017-06-27 12:40:18 -07003773 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003774 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003775 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003776 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003777 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003778 // check if buffer size is set for container layer.
3779 if (w > 0 || h > 0) {
3780 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3781 int(w), int(h));
3782 return BAD_VALUE;
3783 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003784 result = createContainerLayer(client,
3785 uniqueName, w, h, flags,
3786 handle, &layer);
3787 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003788 default:
3789 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003790 break;
3791 }
3792
Dan Stoza7d89d062015-04-30 13:29:25 -07003793 if (result != NO_ERROR) {
3794 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003795 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003796
Chia-I Wuab0c3192017-08-01 11:29:00 -07003797 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3798 // TODO b/64227542
3799 if (windowType == 441731) {
3800 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3801 layer->setPrimaryDisplayOnly();
3802 }
3803
Albert Chaulk479c60c2017-01-27 14:21:34 -05003804 layer->setInfo(windowType, ownerUid);
3805
Robert Carr1f0a16a2016-10-24 16:27:39 -07003806 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003807 if (result != NO_ERROR) {
3808 return result;
3809 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003810 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003811
3812 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003813 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003814}
3815
Cody Northropbc755282017-03-31 12:00:08 -06003816String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3817{
3818 bool matchFound = true;
3819 uint32_t dupeCounter = 0;
3820
3821 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3822 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3823
Dan Stoza436ccf32018-06-21 12:10:12 -07003824 // Grab the state lock since we're accessing mCurrentState
3825 Mutex::Autolock lock(mStateLock);
3826
Cody Northropbc755282017-03-31 12:00:08 -06003827 // Loop over layers until we're sure there is no matching name
3828 while (matchFound) {
3829 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003830 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003831 if (layer->getName() == uniqueName) {
3832 matchFound = true;
3833 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3834 }
3835 });
3836 }
3837
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003838 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3839 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003840
3841 return uniqueName;
3842}
3843
Marissa Wallfd668622018-05-10 10:21:13 -07003844status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3845 uint32_t w, uint32_t h, uint32_t flags,
3846 PixelFormat& format, sp<IBinder>* handle,
3847 sp<IGraphicBufferProducer>* gbp,
3848 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003849 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003850 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003851 case PIXEL_FORMAT_TRANSPARENT:
3852 case PIXEL_FORMAT_TRANSLUCENT:
3853 format = PIXEL_FORMAT_RGBA_8888;
3854 break;
3855 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003856 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003857 break;
3858 }
3859
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003860 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003861 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003862 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003863 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003864 *handle = layer->getHandle();
3865 *gbp = layer->getProducer();
3866 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003867 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003868
Marissa Wallfd668622018-05-10 10:21:13 -07003869 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003870 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003871}
3872
Marissa Wall61c58622018-07-18 10:12:20 -07003873status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3874 uint32_t w, uint32_t h, uint32_t flags,
3875 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003876 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003877 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003878 *handle = layer->getHandle();
3879 *outLayer = layer;
3880
3881 return NO_ERROR;
3882}
3883
chaviw13fdc492017-06-27 12:40:18 -07003884status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003885 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003886 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003887{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003888 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003889 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003890 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003891}
3892
Robert Carr6b3f6c52018-08-13 13:05:17 -07003893status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3894 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3895 sp<IBinder>* handle, sp<Layer>* outLayer)
3896{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003897 *outLayer =
3898 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003899 *handle = (*outLayer)->getHandle();
3900 return NO_ERROR;
3901}
3902
3903
Mathias Agopianac9fa422013-02-11 16:40:36 -08003904status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003905{
Robert Carr9524cb32017-02-13 11:32:32 -08003906 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003907 status_t err = NO_ERROR;
3908 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003909 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003910 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003911 err = removeLayer(l);
3912 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3913 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003914 }
3915 return err;
3916}
3917
Robert Carr2e102c92018-10-23 12:11:15 -07003918void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3919 mLayersPendingRemoval.add(layer);
3920 mLayersRemoved = true;
3921 setTransactionFlags(eTransactionNeeded);
3922}
3923
Robert Carr695d5282018-12-18 15:27:58 -08003924void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003925{
Robert Carr2e102c92018-10-23 12:11:15 -07003926 Mutex::Autolock lock(mStateLock);
3927 markLayerPendingRemovalLocked(mStateLock, layer);
Robert Carr695d5282018-12-18 15:27:58 -08003928 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003929}
3930
Mathias Agopianb60314a2012-04-10 22:09:54 -07003931// ---------------------------------------------------------------------------
3932
Andy McFadden13a082e2012-08-24 10:16:42 -07003933void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003934 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003935 if (!displayToken) return;
3936
Jesse Hall01e29052013-02-19 16:13:35 -08003937 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003938 Vector<ComposerState> state;
3939 Vector<DisplayState> displays;
3940 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003941 d.what = DisplayState::eDisplayProjectionChanged |
3942 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003943 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003944 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003945 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003946 d.frame.makeInvalid();
3947 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003948 d.width = 0;
3949 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003950 displays.add(d);
3951 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003952
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003953 const auto display = getDisplayDevice(displayToken);
3954 if (!display) return;
3955
Dominik Laskowskie9774092018-12-11 10:04:24 -08003956 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003957
Dominik Laskowski075d3172018-05-24 15:50:06 -07003958 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003959 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003960 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003961
Brian Andersond0010582017-03-07 13:20:31 -08003962 // Use phase of 0 since phase is not known.
3963 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003964 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3965 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003966}
3967
3968void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003969 // Async since we may be called from the main thread.
3970 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003971}
3972
Dominik Laskowskie9774092018-12-11 10:04:24 -08003973void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003974 if (display->isVirtual()) {
3975 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003976 return;
3977 }
3978
Dominik Laskowski075d3172018-05-24 15:50:06 -07003979 const auto displayId = display->getId();
3980 LOG_ALWAYS_FATAL_IF(!displayId);
3981
Dominik Laskowski34157762018-10-31 13:07:19 -07003982 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003983
3984 int currentMode = display->getPowerMode();
3985 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003986 return;
3987 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003988
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003989 display->setPowerMode(mode);
3990
Lloyd Pique4dccc412018-01-22 17:21:36 -08003991 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003992 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003993 }
3994
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003995 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003996 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003997 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003998 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003999 if (mUseScheduler) {
4000 mScheduler->onScreenAcquired(mAppConnectionHandle);
4001 } else {
4002 mEventThread->onScreenAcquired();
4003 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004004 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004005 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004006
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004007 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004008 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004009 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004010
4011 struct sched_param param = {0};
4012 param.sched_priority = 1;
4013 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4014 ALOGW("Couldn't set SCHED_FIFO on display on");
4015 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004016 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004017 // Turn off the display
4018 struct sched_param param = {0};
4019 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4020 ALOGW("Couldn't set SCHED_OTHER on display off");
4021 }
4022
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004023 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004024 if (mUseScheduler) {
4025 mScheduler->disableHardwareVsync(true);
4026 } else {
4027 disableHardwareVsync(true); // also cancels any in-progress resync
4028 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004029 if (mUseScheduler) {
4030 mScheduler->onScreenReleased(mAppConnectionHandle);
4031 } else {
4032 mEventThread->onScreenReleased();
4033 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004034 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004035
Dominik Laskowski075d3172018-05-24 15:50:06 -07004036 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004037 mVisibleRegionsDirty = true;
4038 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004039 } else if (mode == HWC_POWER_MODE_DOZE ||
4040 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004041 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004042 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004043 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004044 if (mUseScheduler) {
4045 mScheduler->onScreenAcquired(mAppConnectionHandle);
4046 } else {
4047 mEventThread->onScreenAcquired();
4048 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004049 resyncToHardwareVsync(true);
4050 }
4051 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4052 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004053 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004054 if (mUseScheduler) {
4055 mScheduler->disableHardwareVsync(true);
4056 } else {
4057 disableHardwareVsync(true); // also cancels any in-progress resync
4058 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004059 if (mUseScheduler) {
4060 mScheduler->onScreenReleased(mAppConnectionHandle);
4061 } else {
4062 mEventThread->onScreenReleased();
4063 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004064 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004065 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004066 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004067 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004068 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004069 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004070
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004071 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004072 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004073 }
4074
Dominik Laskowski34157762018-10-31 13:07:19 -07004075 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004076}
4077
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004078void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004079 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004080 const auto display = getDisplayDevice(displayToken);
4081 if (!display) {
4082 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4083 displayToken.get());
4084 } else if (display->isVirtual()) {
4085 ALOGW("Attempt to set power mode %d for virtual display", mode);
4086 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004087 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004088 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004089 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004090}
4091
4092// ---------------------------------------------------------------------------
4093
Lloyd Pique755e3192018-01-31 16:46:15 -08004094status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4095 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004096 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004097
Mathias Agopianbd115332013-04-18 16:41:04 -07004098 IPCThreadState* ipc = IPCThreadState::self();
4099 const int pid = ipc->getCallingPid();
4100 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004101
Mathias Agopianbd115332013-04-18 16:41:04 -07004102 if ((uid != AID_SHELL) &&
4103 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004104 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4105 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004106 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004107 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004108 // (this would indicate SF is stuck, but we want to be able to
4109 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004110 status_t err = mStateLock.timedLock(s2ns(1));
4111 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004112 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004113 StringAppendF(&result,
4114 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4115 "(no locks held)\n",
4116 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004117 }
4118
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004119 bool dumpAll = true;
4120 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004121 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004122
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004123 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004124 if ((index < numArgs) &&
4125 (args[index] == String16("--list"))) {
4126 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004127 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004128 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004129 }
4130
4131 if ((index < numArgs) &&
4132 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004133 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004134 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004135 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004136 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004137
4138 if ((index < numArgs) &&
4139 (args[index] == String16("--latency-clear"))) {
4140 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004141 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004142 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004143 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004144
4145 if ((index < numArgs) &&
4146 (args[index] == String16("--dispsync"))) {
4147 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004148 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004149 dumpAll = false;
4150 }
Dan Stozab90cf072015-03-05 11:05:59 -08004151
4152 if ((index < numArgs) &&
4153 (args[index] == String16("--static-screen"))) {
4154 index++;
4155 dumpStaticScreenStats(result);
4156 dumpAll = false;
4157 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004158
4159 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004160 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004161 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004162 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004163 dumpAll = false;
4164 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004165
4166 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4167 index++;
4168 dumpWideColorInfo(result);
4169 dumpAll = false;
4170 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004171
4172 if ((index < numArgs) &&
4173 (args[index] == String16("--enable-layer-stats"))) {
4174 index++;
4175 mLayerStats.enable();
4176 dumpAll = false;
4177 }
4178
4179 if ((index < numArgs) &&
4180 (args[index] == String16("--disable-layer-stats"))) {
4181 index++;
4182 mLayerStats.disable();
4183 dumpAll = false;
4184 }
4185
4186 if ((index < numArgs) &&
4187 (args[index] == String16("--clear-layer-stats"))) {
4188 index++;
4189 mLayerStats.clear();
4190 dumpAll = false;
4191 }
4192
4193 if ((index < numArgs) &&
4194 (args[index] == String16("--dump-layer-stats"))) {
4195 index++;
4196 mLayerStats.dump(result);
4197 dumpAll = false;
4198 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004199
4200 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004201 (args[index] == String16("--frame-composition"))) {
4202 index++;
4203 dumpFrameCompositionInfo(result);
4204 dumpAll = false;
4205 }
4206
4207 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004208 (args[index] == String16("--display-identification"))) {
4209 index++;
4210 dumpDisplayIdentificationData(result);
4211 dumpAll = false;
4212 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004213
4214 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4215 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004216 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004217 dumpAll = false;
4218 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004219 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004220
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004221 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004222 if (asProto) {
4223 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4224 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4225 } else {
4226 dumpAllLocked(args, index, result);
4227 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004228 }
4229
Mathias Agopian9795c422009-08-26 16:36:26 -07004230 if (locked) {
4231 mStateLock.unlock();
4232 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004233 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004234 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004235 return NO_ERROR;
4236}
4237
Yiwei Zhang5434a782018-12-05 18:06:32 -08004238void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4239 std::string& result) const {
4240 mCurrentState.traverseInZOrder(
4241 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004242}
4243
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004244void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004245 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004246 String8 name;
4247 if (index < args.size()) {
4248 name = String8(args[index]);
4249 index++;
4250 }
4251
Dominik Laskowski075d3172018-05-24 15:50:06 -07004252 if (const auto displayId = getInternalDisplayId();
4253 displayId && getHwComposer().isConnected(*displayId)) {
4254 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004255 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004256 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004257 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004258
4259 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004260 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004261 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004262 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004263 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004264 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004265 }
Robert Carr2047fae2016-11-28 14:09:09 -08004266 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004267 }
4268}
4269
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004270void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004271 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004272 String8 name;
4273 if (index < args.size()) {
4274 name = String8(args[index]);
4275 index++;
4276 }
4277
Robert Carr2047fae2016-11-28 14:09:09 -08004278 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004279 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004280 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004281 }
Robert Carr2047fae2016-11-28 14:09:09 -08004282 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004283
Svetoslavd85084b2014-03-20 10:28:31 -07004284 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004285}
4286
Jamie Gennis6547ff42013-07-16 20:12:42 -07004287// This should only be called from the main thread. Otherwise it would need
4288// the lock and should use mCurrentState rather than mDrawingState.
4289void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004290 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004291 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004292 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004293
4294 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4295}
4296
Yiwei Zhang5434a782018-12-05 18:06:32 -08004297void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004298 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004299
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004300 if (isLayerTripleBufferingDisabled())
4301 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004302
Yiwei Zhang5434a782018-12-05 18:06:32 -08004303 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4304 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4305 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4306 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4307 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4308 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004309 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004310}
4311
Yiwei Zhang5434a782018-12-05 18:06:32 -08004312void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4313 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004314 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4315 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004316 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004317 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004318 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004319 }
David Sodman4a36e932017-11-07 14:29:47 -08004320 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004321 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004322 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004323 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4324 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004325}
4326
Dan Stozae77c7662016-05-13 11:37:28 -07004327void SurfaceFlinger::recordBufferingStats(const char* layerName,
4328 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004329 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4330 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004331 for (const auto& segment : history) {
4332 if (!segment.usedThirdBuffer) {
4333 stats.twoBufferTime += segment.totalTime;
4334 }
4335 if (segment.occupancyAverage < 1.0f) {
4336 stats.doubleBufferedTime += segment.totalTime;
4337 } else if (segment.occupancyAverage < 2.0f) {
4338 stats.tripleBufferedTime += segment.totalTime;
4339 }
4340 ++stats.numSegments;
4341 stats.totalTime += segment.totalTime;
4342 }
4343}
4344
Yiwei Zhang5434a782018-12-05 18:06:32 -08004345void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4346 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004347
4348 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4349 const size_t count = currentLayers.size();
4350 for (size_t i=0 ; i<count ; i++) {
4351 currentLayers[i]->dumpFrameEvents(result);
4352 }
4353}
4354
Yiwei Zhang5434a782018-12-05 18:06:32 -08004355void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004356 result.append("Buffering stats:\n");
4357 result.append(" [Layer name] <Active time> <Two buffer> "
4358 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004359 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004360 typedef std::tuple<std::string, float, float, float> BufferTuple;
4361 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004362 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004363 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004364 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004365 if (stats.numSegments == 0) {
4366 continue;
4367 }
4368 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4369 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4370 stats.totalTime;
4371 float doubleBufferRatio = static_cast<float>(
4372 stats.doubleBufferedTime) / stats.totalTime;
4373 float tripleBufferRatio = static_cast<float>(
4374 stats.tripleBufferedTime) / stats.totalTime;
4375 sorted.insert({activeTime, {name, twoBufferRatio,
4376 doubleBufferRatio, tripleBufferRatio}});
4377 }
4378 for (const auto& sortedPair : sorted) {
4379 float activeTime = sortedPair.first;
4380 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004381 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4382 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004383 }
4384 result.append("\n");
4385}
4386
Yiwei Zhang5434a782018-12-05 18:06:32 -08004387void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004388 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004389 const auto displayId = display->getId();
4390 if (!displayId) {
4391 continue;
4392 }
4393 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004394 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004395 continue;
4396 }
4397
Yiwei Zhang5434a782018-12-05 18:06:32 -08004398 StringAppendF(&result,
4399 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4400 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004401 uint8_t port;
4402 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004403 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004404 result.append("no identification data\n");
4405 continue;
4406 }
4407
4408 if (!isEdid(data)) {
4409 result.append("unknown identification data: ");
4410 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004411 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004412 }
4413 result.append("\n");
4414 continue;
4415 }
4416
4417 const auto edid = parseEdid(data);
4418 if (!edid) {
4419 result.append("invalid EDID: ");
4420 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004421 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004422 }
4423 result.append("\n");
4424 continue;
4425 }
4426
Yiwei Zhang5434a782018-12-05 18:06:32 -08004427 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004428 result.append(edid->displayName.data(), edid->displayName.length());
4429 result.append("\"\n");
4430 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004431}
4432
Yiwei Zhang5434a782018-12-05 18:06:32 -08004433void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4434 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4435 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4436 StringAppendF(&result, "DisplayColorSetting: %s\n",
4437 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004438
4439 // TODO: print out if wide-color mode is active or not
4440
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004441 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004442 const auto displayId = display->getId();
4443 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004444 continue;
4445 }
4446
Yiwei Zhang5434a782018-12-05 18:06:32 -08004447 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004448 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004449 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004450 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004451 }
4452
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004453 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004454 StringAppendF(&result, " Current color mode: %s (%d)\n",
4455 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004456 }
4457 result.append("\n");
4458}
4459
Yiwei Zhang5434a782018-12-05 18:06:32 -08004460void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004461 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004462 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4463 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004464 continue;
4465 }
4466
Dominik Laskowski05275f12018-11-01 15:03:24 -07004467 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004468 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4469 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004470 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004471 compositionInfo.dump(result, nullptr);
4472 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004473 }
4474 }
David Sodman7e4ae112018-02-09 15:02:28 -08004475}
4476
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004477LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004478 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004479 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4480 const State& state = useDrawing ? mDrawingState : mCurrentState;
4481 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004482 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004483 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004484 });
4485
4486 return layersProto;
4487}
4488
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004489LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004490 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004491
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004492 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004493 resolution->set_w(display.getWidth());
4494 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004495
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004496 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4497 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4498 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004499
Dominik Laskowski075d3172018-05-24 15:50:06 -07004500 const auto displayId = display.getId();
4501 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004502 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004503 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004504 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004505 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004506 }
4507 });
4508
4509 return layersProto;
4510}
4511
Mathias Agopian74d211a2013-04-22 16:55:35 +02004512void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004513 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004514 bool colorize = false;
4515 if (index < args.size()
4516 && (args[index] == String16("--color"))) {
4517 colorize = true;
4518 index++;
4519 }
4520
4521 Colorizer colorizer(colorize);
4522
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004523 // figure out if we're stuck somewhere
4524 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004525 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004526 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4527
4528 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004529 * Dump library configuration.
4530 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004531
4532 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004533 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004534 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004535 appendSfConfigString(result);
4536 appendUiConfigString(result);
4537 appendGuiConfigString(result);
4538 result.append("\n");
4539
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004540 result.append("\nDisplay identification data:\n");
4541 dumpDisplayIdentificationData(result);
4542
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004543 result.append("\nWide-Color information:\n");
4544 dumpWideColorInfo(result);
4545
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004546 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004547 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004548 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004549 result.append(SyncFeatures::getInstance().toString());
4550 result.append("\n");
4551
Andy McFadden41d67d72014-04-25 16:58:34 -07004552 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004553 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004554 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004555
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004556 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4557 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004558 if (const auto displayId = getInternalDisplayId();
4559 displayId && getHwComposer().isConnected(*displayId)) {
4560 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004561 StringAppendF(&result,
4562 "Display %s: app phase %" PRId64 " ns, "
4563 "sf phase %" PRId64 " ns, "
4564 "early app phase %" PRId64 " ns, "
4565 "early sf phase %" PRId64 " ns, "
4566 "early app gl phase %" PRId64 " ns, "
4567 "early sf gl phase %" PRId64 " ns, "
4568 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4569 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4570 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4571 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004572 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004573 result.append("\n");
4574
Dan Stozab90cf072015-03-05 11:05:59 -08004575 // Dump static screen stats
4576 result.append("\n");
4577 dumpStaticScreenStats(result);
4578 result.append("\n");
4579
Yiwei Zhang5434a782018-12-05 18:06:32 -08004580 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004581
Dan Stozae77c7662016-05-13 11:37:28 -07004582 dumpBufferingStats(result);
4583
Andy McFadden4803b742012-09-24 19:07:20 -07004584 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004585 * Dump the visible layer list
4586 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004587 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004588 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4589 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4590 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004591 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004592
Chia-I Wu2f884132018-09-13 15:17:58 -07004593 {
4594 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4595 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004596 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004597 result.append("\n");
4598 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004599
David Sodman7e4ae112018-02-09 15:02:28 -08004600 result.append("\nFrame-Composition information:\n");
4601 dumpFrameCompositionInfo(result);
4602 result.append("\n");
4603
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004604 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004605 * Dump Display state
4606 */
4607
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004608 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004609 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004610 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004611 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004612 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004613 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004614 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004615
4616 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004617 * Dump SurfaceFlinger global state
4618 */
4619
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004620 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004621 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004622 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004623
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004624 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004625
Dominik Laskowski075d3172018-05-24 15:50:06 -07004626 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004627 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004628 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4629 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004630 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004631 StringAppendF(&result,
4632 " transaction-flags : %08x\n"
4633 " gpu_to_cpu_unsupported : %d\n",
4634 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004635
Dominik Laskowski075d3172018-05-24 15:50:06 -07004636 if (const auto displayId = getInternalDisplayId();
4637 displayId && getHwComposer().isConnected(*displayId)) {
4638 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004639 StringAppendF(&result,
4640 " refresh-rate : %f fps\n"
4641 " x-dpi : %f\n"
4642 " y-dpi : %f\n",
4643 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4644 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004645 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004646
Yiwei Zhang5434a782018-12-05 18:06:32 -08004647 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004648
Yiwei Zhang5434a782018-12-05 18:06:32 -08004649 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004650 /*
4651 * VSYNC state
4652 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004653 if (mUseScheduler) {
4654 mScheduler->dump(mAppConnectionHandle, result);
4655 } else {
4656 mEventThread->dump(result);
4657 }
Dan Stozae22aec72016-08-01 13:20:59 -07004658 result.append("\n");
4659
4660 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004661 * Tracing state
4662 */
4663 mTracing.dump(result);
4664 result.append("\n");
4665
4666 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004667 * HWC layer minidump
4668 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004669 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004670 const auto displayId = display->getId();
4671 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004672 continue;
4673 }
4674
Yiwei Zhang5434a782018-12-05 18:06:32 -08004675 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004676 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004677 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004678 result.append("\n");
4679 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004680
4681 /*
4682 * Dump HWComposer state
4683 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004684 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004685 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004686 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004687 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004688 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004689 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004690
4691 /*
4692 * Dump gralloc state
4693 */
4694 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4695 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004696
4697 /*
4698 * Dump VrFlinger state if in use.
4699 */
4700 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4701 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004702 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004703 result.append("\n");
4704 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004705}
4706
Dominik Laskowski075d3172018-05-24 15:50:06 -07004707const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004708 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004709 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004710 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004711 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004712 }
4713 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004714
Dominik Laskowski34157762018-10-31 13:07:19 -07004715 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004716 static const Vector<sp<Layer>> empty;
4717 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004718}
4719
Keun young Park63f165f2012-08-31 10:53:36 -07004720bool SurfaceFlinger::startDdmConnection()
4721{
4722 void* libddmconnection_dso =
4723 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4724 if (!libddmconnection_dso) {
4725 return false;
4726 }
4727 void (*DdmConnection_start)(const char* name);
4728 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004729 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004730 if (!DdmConnection_start) {
4731 dlclose(libddmconnection_dso);
4732 return false;
4733 }
4734 (*DdmConnection_start)(getServiceName());
4735 return true;
4736}
4737
Chia-I Wu28f320b2018-05-03 11:02:56 -07004738void SurfaceFlinger::updateColorMatrixLocked() {
4739 mat4 colorMatrix;
4740 if (mGlobalSaturationFactor != 1.0f) {
4741 // Rec.709 luma coefficients
4742 float3 luminance{0.213f, 0.715f, 0.072f};
4743 luminance *= 1.0f - mGlobalSaturationFactor;
4744 mat4 saturationMatrix = mat4(
4745 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4746 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4747 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4748 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4749 );
4750 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4751 } else {
4752 colorMatrix = mClientColorMatrix * mDaltonizer();
4753 }
4754
4755 if (mCurrentState.colorMatrix != colorMatrix) {
4756 mCurrentState.colorMatrix = colorMatrix;
4757 mCurrentState.colorMatrixChanged = true;
4758 setTransactionFlags(eTransactionNeeded);
4759 }
4760}
4761
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004762status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004763#pragma clang diagnostic push
4764#pragma clang diagnostic error "-Wswitch-enum"
4765 switch (static_cast<ISurfaceComposerTag>(code)) {
4766 // These methods should at minimum make sure that the client requested
4767 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004768 case BOOT_FINISHED:
4769 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004770 case CREATE_CONNECTION:
4771 case CREATE_DISPLAY:
4772 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004773 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004774 case GET_ACTIVE_COLOR_MODE:
4775 case GET_ANIMATION_FRAME_STATS:
4776 case GET_HDR_CAPABILITIES:
4777 case SET_ACTIVE_CONFIG:
4778 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004779 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004780 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004781 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004782 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4783 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004784 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4785 IPCThreadState* ipc = IPCThreadState::self();
4786 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4787 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004788 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004789 }
Robert Carr1db73f62016-12-21 12:58:51 -08004790 return OK;
4791 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004792 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004793 IPCThreadState* ipc = IPCThreadState::self();
4794 const int pid = ipc->getCallingPid();
4795 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004796 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4797 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004798 return PERMISSION_DENIED;
4799 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004800 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004801 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004802 // Used by apps to hook Choreographer to SurfaceFlinger.
4803 case CREATE_DISPLAY_EVENT_CONNECTION:
4804 // The following calls are currently used by clients that do not
4805 // request necessary permissions. However, they do not expose any secret
4806 // information, so it is OK to pass them.
4807 case AUTHENTICATE_SURFACE:
4808 case GET_ACTIVE_CONFIG:
4809 case GET_BUILT_IN_DISPLAY:
4810 case GET_DISPLAY_COLOR_MODES:
4811 case GET_DISPLAY_CONFIGS:
4812 case GET_DISPLAY_STATS:
4813 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4814 // Calling setTransactionState is safe, because you need to have been
4815 // granted a reference to Client* and Handle* to do anything with it.
4816 case SET_TRANSACTION_STATE:
4817 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004818 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004819 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004820 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004821 return OK;
4822 }
4823 case CAPTURE_LAYERS:
4824 case CAPTURE_SCREEN: {
4825 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004826 IPCThreadState* ipc = IPCThreadState::self();
4827 const int pid = ipc->getCallingPid();
4828 const int uid = ipc->getCallingUid();
4829 if ((uid != AID_GRAPHICS) &&
4830 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4831 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4832 return PERMISSION_DENIED;
4833 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004834 return OK;
4835 }
4836 // The following codes are deprecated and should never be allowed to access SF.
4837 case CONNECT_DISPLAY_UNUSED:
4838 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4839 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4840 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004841 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004842 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004843
4844 // These codes are used for the IBinder protocol to either interrogate the recipient
4845 // side of the transaction for its canonical interface descriptor or to dump its state.
4846 // We let them pass by default.
4847 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4848 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4849 code == IBinder::SYSPROPS_TRANSACTION) {
4850 return OK;
4851 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004852 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004853 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004854 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004855 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4856 return OK;
4857 }
4858 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4859 return PERMISSION_DENIED;
4860#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004861}
4862
Ana Krulec13be8ad2018-08-21 02:43:56 +00004863status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4864 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004865 status_t credentialCheck = CheckTransactCodeCredentials(code);
4866 if (credentialCheck != OK) {
4867 return credentialCheck;
4868 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004869
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004870 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4871 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004872 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004873 IPCThreadState* ipc = IPCThreadState::self();
4874 const int uid = ipc->getCallingUid();
4875 if (CC_UNLIKELY(uid != AID_SYSTEM
4876 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004877 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004878 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004879 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004880 return PERMISSION_DENIED;
4881 }
4882 int n;
4883 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004884 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004885 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004886 return NO_ERROR;
4887 case 1002: // SHOW_UPDATES
4888 n = data.readInt32();
4889 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004890 invalidateHwcGeometry();
4891 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004892 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004893 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004894 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004895 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004896 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004897 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004898 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004899 setTransactionFlags(
4900 eTransactionNeeded|
4901 eDisplayTransactionNeeded|
4902 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004903 return NO_ERROR;
4904 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004905 case 1006:{ // send empty update
4906 signalRefresh();
4907 return NO_ERROR;
4908 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004909 case 1008: // toggle use of hw composer
4910 n = data.readInt32();
4911 mDebugDisableHWC = n ? 1 : 0;
4912 invalidateHwcGeometry();
4913 repaintEverything();
4914 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004915 case 1009: // toggle use of transform hint
4916 n = data.readInt32();
4917 mDebugDisableTransformHint = n ? 1 : 0;
4918 invalidateHwcGeometry();
4919 repaintEverything();
4920 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004921 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004922 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004923 reply->writeInt32(0);
4924 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004925 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004926 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004927 return NO_ERROR;
4928 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004929 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004930 if (!display) {
4931 return NAME_NOT_FOUND;
4932 }
4933
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004934 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004935 return NO_ERROR;
4936 }
4937 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004938 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004939 // daltonize
4940 n = data.readInt32();
4941 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004942 case 1:
4943 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4944 break;
4945 case 2:
4946 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4947 break;
4948 case 3:
4949 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4950 break;
4951 default:
4952 mDaltonizer.setType(ColorBlindnessType::None);
4953 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004954 }
4955 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004956 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004957 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004958 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004959 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004960
4961 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004962 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004963 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004964 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004965 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004966 // apply a color matrix
4967 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004968 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004969 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004970 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004971 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004972 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004973 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004974 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004975 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004976 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004977 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004978
4979 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4980 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004981 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004982 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4983 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4984 }
4985
Chia-I Wu28f320b2018-05-03 11:02:56 -07004986 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004987 return NO_ERROR;
4988 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004989 // This is an experimental interface
4990 // Needs to be shifted to proper binder interface when we productize
4991 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004992 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004993 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004994 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004995 return NO_ERROR;
4996 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004997 case 1017: {
4998 n = data.readInt32();
4999 mForceFullDamage = static_cast<bool>(n);
5000 return NO_ERROR;
5001 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005002 case 1018: { // Modify Choreographer's phase offset
5003 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005004 if (mUseScheduler) {
5005 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5006 } else {
5007 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5008 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005009 return NO_ERROR;
5010 }
5011 case 1019: { // Modify SurfaceFlinger's phase offset
5012 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005013 if (mUseScheduler) {
5014 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5015 } else {
5016 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5017 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005018 return NO_ERROR;
5019 }
Irvel468051e2016-06-13 16:44:44 -07005020 case 1020: { // Layer updates interceptor
5021 n = data.readInt32();
5022 if (n) {
5023 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005024 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005025 }
5026 else{
5027 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005028 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005029 }
5030 return NO_ERROR;
5031 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005032 case 1021: { // Disable HWC virtual displays
5033 n = data.readInt32();
5034 mUseHwcVirtualDisplays = !n;
5035 return NO_ERROR;
5036 }
Romain Guy0147a172017-06-01 13:53:56 -07005037 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005038 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005039 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005040
Chia-I Wu28f320b2018-05-03 11:02:56 -07005041 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005042 return NO_ERROR;
5043 }
Romain Guy54f154a2017-10-24 21:40:32 +01005044 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005045 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005046 invalidateHwcGeometry();
5047 repaintEverything();
5048 return NO_ERROR;
5049 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005050 // Deprecate, use 1030 to check whether the device is color managed.
5051 case 1024: {
5052 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005053 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005054 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005055 n = data.readInt32();
5056 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005057 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005058 mTracing.enable();
5059 doTracing("tracing.enable");
5060 reply->writeInt32(NO_ERROR);
5061 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005062 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005063 status_t err = mTracing.disable();
5064 reply->writeInt32(err);
5065 }
5066 return NO_ERROR;
5067 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005068 case 1026: { // Get layer tracing status
5069 reply->writeBool(mTracing.isEnabled());
5070 return NO_ERROR;
5071 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005072 // Is a DisplayColorSetting supported?
5073 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005074 const auto display = getDefaultDisplayDevice();
5075 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005076 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005077 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005078
5079 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5080 switch (setting) {
5081 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005082 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005083 break;
5084 case DisplayColorSetting::UNMANAGED:
5085 reply->writeBool(true);
5086 break;
5087 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005088 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005089 break;
5090 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005091 reply->writeBool(
5092 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005093 break;
5094 }
5095 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005096 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005097 // Is VrFlinger active?
5098 case 1028: {
5099 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005100 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005101 return NO_ERROR;
5102 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005103 // Is device color managed?
5104 case 1030: {
5105 reply->writeBool(useColorManagement);
5106 return NO_ERROR;
5107 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005108 // Override default composition data space
5109 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5110 // && adb shell stop zygote && adb shell start zygote
5111 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5112 // adb shell stop zygote && adb shell start zygote
5113 case 1031: {
5114 Mutex::Autolock _l(mStateLock);
5115 n = data.readInt32();
5116 if (n) {
5117 n = data.readInt32();
5118 if (n) {
5119 Dataspace dataspace = static_cast<Dataspace>(n);
5120 if (!validateCompositionDataspace(dataspace)) {
5121 return BAD_VALUE;
5122 }
5123 mDefaultCompositionDataspace = dataspace;
5124 }
5125 n = data.readInt32();
5126 if (n) {
5127 Dataspace dataspace = static_cast<Dataspace>(n);
5128 if (!validateCompositionDataspace(dataspace)) {
5129 return BAD_VALUE;
5130 }
5131 mWideColorGamutCompositionDataspace = dataspace;
5132 }
5133 } else {
5134 // restore composition data space.
5135 mDefaultCompositionDataspace = defaultCompositionDataspace;
5136 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5137 }
5138 return NO_ERROR;
5139 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005140 }
5141 }
5142 return err;
5143}
5144
Steven Thomas6d8110b2017-08-31 18:24:21 -07005145void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005146 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005147 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005148}
5149
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005150// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5151class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005152public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005153 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5154 ~WindowDisconnector() {
5155 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005156 }
5157
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005158private:
5159 ANativeWindow* mWindow;
5160 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005161};
5162
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005163status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005164 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5165 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005166 uint32_t reqWidth, uint32_t reqHeight,
5167 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005168 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005169 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005170
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005171 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005172
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005173 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5174
Chia-I Wu20261cb2018-08-23 12:55:44 -07005175 sp<DisplayDevice> display;
5176 {
5177 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005178
Chia-I Wu20261cb2018-08-23 12:55:44 -07005179 display = getDisplayDeviceLocked(displayToken);
5180 if (!display) return BAD_VALUE;
5181
Chia-I Wucb023152018-08-28 12:57:23 -07005182 // set the requested width/height to the logical display viewport size
5183 // by default
5184 if (reqWidth == 0 || reqHeight == 0) {
5185 reqWidth = uint32_t(display->getViewport().width());
5186 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005187 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005188 }
5189
Peiyong Lin0e003c92018-09-17 11:09:51 -07005190 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5191 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005192
5193 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005194 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005195 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5196 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005197}
5198
5199status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005200 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5201 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005202 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005203 ATRACE_CALL();
5204
5205 class LayerRenderArea : public RenderArea {
5206 public:
Robert Carr578038f2018-03-09 12:25:24 -08005207 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005208 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5209 bool childrenOnly)
5210 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005211 mLayer(layer),
5212 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005213 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005214 mFlinger(flinger),
5215 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005216 const ui::Transform& getTransform() const override { return mTransform; }
Ady Abraham83729882018-12-07 12:26:48 -08005217 Rect getBounds() const override { return mLayer->getBufferSize(StateSet::Drawing); }
Marissa Wall61c58622018-07-18 10:12:20 -07005218 int getHeight() const override {
Ady Abraham83729882018-12-07 12:26:48 -08005219 return mLayer->getBufferSize(StateSet::Drawing).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005220 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005221 int getWidth() const override {
Ady Abraham83729882018-12-07 12:26:48 -08005222 return mLayer->getBufferSize(StateSet::Drawing).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005223 }
chaviwa76b2712017-09-20 12:02:26 -07005224 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005225 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005226 Rect getSourceCrop() const override {
5227 if (mCrop.isEmpty()) {
5228 return getBounds();
5229 } else {
5230 return mCrop;
5231 }
5232 }
Robert Carr578038f2018-03-09 12:25:24 -08005233 class ReparentForDrawing {
5234 public:
5235 const sp<Layer>& oldParent;
5236 const sp<Layer>& newParent;
5237
5238 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5239 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005240 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005241 }
Robert Carr15eae092018-03-23 13:43:53 -07005242 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005243 };
5244
5245 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005246 const Rect sourceCrop = getSourceCrop();
5247 // no need to check rotation because there is none
5248 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5249 sourceCrop.height() != getReqHeight();
5250
Robert Carr578038f2018-03-09 12:25:24 -08005251 if (!mChildrenOnly) {
5252 mTransform = mLayer->getTransform().inverse();
5253 drawLayers();
5254 } else {
5255 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005256 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005257 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5258 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005259
5260 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5261 drawLayers();
5262 }
5263 }
chaviwa76b2712017-09-20 12:02:26 -07005264
chaviwa76b2712017-09-20 12:02:26 -07005265 private:
chaviw7206d492017-11-10 16:16:12 -08005266 const sp<Layer> mLayer;
5267 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005268
5269 // In the "childrenOnly" case we reparent the children to a screenshot
5270 // layer which has no properties set and which does not draw.
5271 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005272 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005273 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005274
5275 SurfaceFlinger* mFlinger;
5276 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005277 };
5278
5279 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5280 auto parent = layerHandle->owner.promote();
5281
Robert Carr2e102c92018-10-23 12:11:15 -07005282 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005283 ALOGE("captureLayers called with a removed parent");
5284 return NAME_NOT_FOUND;
5285 }
5286
Robert Carr578038f2018-03-09 12:25:24 -08005287 const int uid = IPCThreadState::self()->getCallingUid();
5288 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Ady Abraham83729882018-12-07 12:26:48 -08005289 if (!forSystem && parent->getCurrentFlags() & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005290 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5291 return PERMISSION_DENIED;
5292 }
5293
chaviw7206d492017-11-10 16:16:12 -08005294 Rect crop(sourceCrop);
5295 if (sourceCrop.width() <= 0) {
5296 crop.left = 0;
Ady Abraham83729882018-12-07 12:26:48 -08005297 crop.right = parent->getBufferSize(StateSet::Current).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005298 }
5299
5300 if (sourceCrop.height() <= 0) {
5301 crop.top = 0;
Ady Abraham83729882018-12-07 12:26:48 -08005302 crop.bottom = parent->getBufferSize(StateSet::Current).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005303 }
5304
5305 int32_t reqWidth = crop.width() * frameScale;
5306 int32_t reqHeight = crop.height() * frameScale;
5307
Chia-I Wu20261cb2018-08-23 12:55:44 -07005308 // really small crop or frameScale
5309 if (reqWidth <= 0) {
5310 reqWidth = 1;
5311 }
5312 if (reqHeight <= 0) {
5313 reqHeight = 1;
5314 }
5315
Peiyong Lin0e003c92018-09-17 11:09:51 -07005316 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005317
Robert Carr578038f2018-03-09 12:25:24 -08005318 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005319 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5320 if (!layer->isVisible()) {
5321 return;
Robert Carr578038f2018-03-09 12:25:24 -08005322 } else if (childrenOnly && layer == parent.get()) {
5323 return;
chaviwa76b2712017-09-20 12:02:26 -07005324 }
5325 visitor(layer);
5326 });
5327 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005328 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005329}
5330
5331status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5332 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005333 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005334 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005335 bool useIdentityTransform) {
5336 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005337
Peiyong Lin0e003c92018-09-17 11:09:51 -07005338 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005339 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5340 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005341 *outBuffer =
5342 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5343 static_cast<android_pixel_format>(reqPixelFormat), 1,
5344 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005345
5346 // This mutex protects syncFd and captureResult for communication of the return values from the
5347 // main thread back to this Binder thread
5348 std::mutex captureMutex;
5349 std::condition_variable captureCondition;
5350 std::unique_lock<std::mutex> captureLock(captureMutex);
5351 int syncFd = -1;
5352 std::optional<status_t> captureResult;
5353
Robert Carr03480e22018-01-04 16:02:06 -08005354 const int uid = IPCThreadState::self()->getCallingUid();
5355 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5356
Dominik Laskowski8c001672018-05-30 16:52:06 -07005357 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005358 // If there is a refresh pending, bug out early and tell the binder thread to try again
5359 // after the refresh.
5360 if (mRefreshPending) {
5361 ATRACE_NAME("Skipping screenshot for now");
5362 std::unique_lock<std::mutex> captureLock(captureMutex);
5363 captureResult = std::make_optional<status_t>(EAGAIN);
5364 captureCondition.notify_one();
5365 return;
5366 }
5367
5368 status_t result = NO_ERROR;
5369 int fd = -1;
5370 {
5371 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005372 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005373 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5374 useIdentityTransform, forSystem, &fd);
5375 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005376 }
5377
5378 {
5379 std::unique_lock<std::mutex> captureLock(captureMutex);
5380 syncFd = fd;
5381 captureResult = std::make_optional<status_t>(result);
5382 captureCondition.notify_one();
5383 }
5384 });
5385
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005386 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005387 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005388 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005389 while (*captureResult == EAGAIN) {
5390 captureResult.reset();
5391 result = postMessageAsync(message);
5392 if (result != NO_ERROR) {
5393 return result;
5394 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005395 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005396 }
5397 result = *captureResult;
5398 }
5399
5400 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005401 sync_wait(syncFd, -1);
5402 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005403 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005404
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005405 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005406}
5407
chaviwa76b2712017-09-20 12:02:26 -07005408void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005409 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005410 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005411 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005412
Lloyd Pique144e1162017-12-20 16:44:52 -08005413 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005414
chaviwa76b2712017-09-20 12:02:26 -07005415 const auto reqWidth = renderArea.getReqWidth();
5416 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005417 const auto sourceCrop = renderArea.getSourceCrop();
5418 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005419
Peiyong Lin0e003c92018-09-17 11:09:51 -07005420 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005421 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005422
Mathias Agopian180f10d2013-04-10 22:55:41 -07005423 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005424 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005425
5426 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005427 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005428 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005429
chaviw50da5042018-04-09 13:49:37 -07005430 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005431 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005432 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005433
chaviwa76b2712017-09-20 12:02:26 -07005434 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005435 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005436 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005437 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005438 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005439}
5440
chaviwa76b2712017-09-20 12:02:26 -07005441status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5442 TraverseLayersFunction traverseLayers,
5443 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005444 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005445 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005446 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005447 ATRACE_CALL();
5448
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005449 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005450
5451 traverseLayers([&](Layer* layer) {
5452 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5453 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005454
Robert Carr03480e22018-01-04 16:02:06 -08005455 // We allow the system server to take screenshots of secure layers for
5456 // use in situations like the Screen-rotation animation and place
5457 // the impetus on WindowManager to not persist them.
5458 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005459 ALOGW("FB is protected: PERMISSION_DENIED");
5460 return PERMISSION_DENIED;
5461 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005462 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005463
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005464 // this binds the given EGLImage as a framebuffer for the
5465 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005466 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005467 if (bufferBond.getStatus() != NO_ERROR) {
5468 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005469 return INVALID_OPERATION;
5470 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005471
Dan Stozaabcda352017-06-01 14:37:39 -07005472 // this will in fact render into our dequeued buffer
5473 // via an FBO, which means we didn't have to create
5474 // an EGLSurface and therefore we're not
5475 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005476 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005477
Peiyong Linfb530cf2018-12-15 05:07:38 +00005478 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005479 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005480 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005481 }
Alec Mouri492bc572018-09-11 21:40:04 +00005482 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005483
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005484 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005485}
5486
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005487// ---------------------------------------------------------------------------
5488
Dan Stoza412903f2017-04-27 13:42:17 -07005489void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5490 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005491}
5492
Dan Stoza412903f2017-04-27 13:42:17 -07005493void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5494 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005495}
5496
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005497void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005498 const LayerVector::Visitor& visitor) {
5499 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005500 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005501 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005502 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005503 continue;
5504 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005505 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005506 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005507 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005508 return;
5509 }
chaviwa76b2712017-09-20 12:02:26 -07005510 if (!layer->isVisible()) {
5511 return;
5512 }
5513 visitor(layer);
5514 });
5515 }
5516}
5517
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005518}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005519
Lloyd Pique074e8122018-07-26 12:57:23 -07005520
Mathias Agopian3f844832013-08-07 21:24:32 -07005521#if defined(__gl_h_)
5522#error "don't include gl/gl.h in this file"
5523#endif
5524
5525#if defined(__gl2_h_)
5526#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005527#endif