blob: 4341eedc31e4b46cf5ac73802b109282bf6d8b5f [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
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.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"
Ana Krulecfefcb582018-08-07 14:22:37 -070095
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070097
David Sodman7e4ae112018-02-09 15:02:28 -080098#include "android-base/stringprintf.h"
99
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900100#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800101#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700102#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800103#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900104#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105
chaviw1d044282017-09-27 12:19:28 -0700106#include <layerproto/LayerProtoParser.h>
107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108#define DISPLAY_COUNT 1
109
110namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700111
Jaesoo Lee43518572017-01-23 19:03:16 +0900112using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113using namespace android::hardware::configstore::V1_0;
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
Steven Thomasb02664d2017-07-26 18:48:28 -0700176} // namespace anonymous
177
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178// ---------------------------------------------------------------------------
179
Mathias Agopian99b49842011-06-27 16:05:52 -0700180const String16 sHardwareTest("android.permission.HARDWARE_TEST");
181const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
182const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
183const String16 sDump("android.permission.DUMP");
184
185// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800186int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
187int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700188int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700189bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800190uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800191bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800192bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800193int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800194// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600195bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700196int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700197bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700198bool SurfaceFlinger::useContextPriority;
Peiyong Lin0256f722018-08-31 15:45:10 -0700199Dataspace SurfaceFlinger::compositionDataSpace = Dataspace::V0_SRGB;
200ui::PixelFormat SurfaceFlinger::compositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700201
Kalle Raitaa099a242017-01-11 11:17:29 -0800202std::string getHwcServiceName() {
203 char value[PROPERTY_VALUE_MAX] = {};
204 property_get("debug.sf.hwc_service_name", value, "default");
205 ALOGI("Using HWComposer service: '%s'", value);
206 return std::string(value);
207}
208
209bool useTrebleTestingOverride() {
210 char value[PROPERTY_VALUE_MAX] = {};
211 property_get("debug.sf.treble_testing_override", value, "false");
212 ALOGI("Treble testing override: '%s'", value);
213 return std::string(value) == "true";
214}
215
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800216std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
217 switch(displayColorSetting) {
218 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700219 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800220 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700221 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800222 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700223 return std::string("Enhanced");
224 default:
225 return std::string("Unknown ") +
226 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800227 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800228}
229
David Sodmanbc815282017-11-05 18:57:52 -0800230SurfaceFlingerBE::SurfaceFlingerBE()
231 : mHwcServiceName(getHwcServiceName()),
232 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800233 mFrameBuckets(),
234 mTotalTime(0),
235 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800236 mComposerSequenceId(0) {
237}
238
Lloyd Pique90c115d2018-09-18 21:39:42 -0700239SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
240 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800241 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700242 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700243 mTransactionPending(false),
244 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700245 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700246 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700248 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800249 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800250 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800251 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800252 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700254 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700255 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700256 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700257 mDebugInTransaction(0),
258 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700259 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700260 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700261 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800262 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800263 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800264 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700265 mVrFlingerRequestsDisplay(false),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700266 mMainThreadId(std::this_thread::get_id()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800267
Lloyd Pique90c115d2018-09-18 21:39:42 -0700268SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
269 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800270 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800271
272 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
273 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
274
275 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
276 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
277
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800278 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700281 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
283
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700284 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
286
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800287 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
289
Steven Thomas050b2c82017-03-06 11:45:16 -0800290 // Vr flinger is only enabled on Daydream ready devices.
291 useVrFlinger = getBool< ISurfaceFlingerConfigs,
292 &ISurfaceFlingerConfigs::useVrFlinger>(false);
293
Fabien Sanglard1971b632017-03-10 14:50:03 -0800294 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
296
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600297 hasWideColorDisplay =
298 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700299 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700300 getBool<V1_2::ISurfaceFlingerConfigs,
301 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
302
303 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
304 if (surfaceFlingerConfigsServiceV1_2) {
305 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
306 [&](Dataspace tmpDataSpace, ui::PixelFormat tmpPixelFormat) {
307 compositionDataSpace = tmpDataSpace;
308 compositionPixelFormat = tmpPixelFormat;
309 });
310 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600311
Peiyong Linb3839ad2018-09-05 15:37:19 -0700312 useContextPriority = getBool<ISurfaceFlingerConfigs,
313 &ISurfaceFlingerConfigs::useContextPriority>(true);
314
Iris Chang7501ed62018-04-30 14:45:42 +0800315 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700316 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
317 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800318 V1_1::DisplayOrientation::ORIENTATION_0);
319
320 switch (primaryDisplayOrientation) {
321 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700322 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800323 break;
324 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700325 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800326 break;
327 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700328 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800329 break;
330 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700331 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800332 break;
333 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700334 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800335
Lloyd Pique90c115d2018-09-18 21:39:42 -0700336 mPrimaryDispSync =
337 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
338 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340 // debugging stuff...
341 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700342
Mathias Agopianb4b17302013-03-20 18:36:41 -0700343 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700344 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700345
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800346 property_get("debug.sf.showupdates", value, "0");
347 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700348
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700349 property_get("debug.sf.ddms", value, "0");
350 mDebugDDMS = atoi(value);
351 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700352 if (!startDdmConnection()) {
353 // start failed, and DDMS debugging not enabled
354 mDebugDDMS = 0;
355 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700356 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700357 ALOGI_IF(mDebugRegion, "showupdates enabled");
358 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700359
360 property_get("debug.sf.disable_backpressure", value, "0");
361 mPropagateBackpressure = !atoi(value);
362 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700363
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800364 property_get("debug.sf.enable_hwc_vds", value, "0");
365 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800366 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800367
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800368 property_get("ro.sf.disable_triple_buffer", value, "1");
369 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800370 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700371
Yiwei Zhang243b3782018-05-15 17:40:04 -0700372 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700373 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
374 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
375
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200376 property_get("debug.sf.early_phase_offset_ns", value, "-1");
377 const int earlySfOffsetNs = atoi(value);
378
379 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
380 const int earlyGlSfOffsetNs = atoi(value);
381
382 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
383 const int earlyAppOffsetNs = atoi(value);
384
385 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
386 const int earlyGlAppOffsetNs = atoi(value);
387
Ana Krulec98b5b242018-08-10 15:03:23 -0700388 property_get("debug.sf.use_scheduler", value, "0");
389 mUseScheduler = atoi(value);
390
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200391 const VSyncModulator::Offsets earlyOffsets =
392 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
393 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
394 const VSyncModulator::Offsets earlyGlOffsets =
395 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
396 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
397 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
398 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700399
Romain Guy11d63f42017-07-20 12:47:14 -0700400 // We should be reading 'persist.sys.sf.color_saturation' here
401 // but since /data may be encrypted, we need to wait until after vold
402 // comes online to attempt to read the property. The property is
403 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800404
405 if (useTrebleTestingOverride()) {
406 // Without the override SurfaceFlinger cannot connect to HIDL
407 // services that are not listed in the manifests. Considered
408 // deriving the setting from the set service name, but it
409 // would be brittle if the name that's not 'default' is used
410 // for production purposes later on.
411 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
412 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800413}
414
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800415void SurfaceFlinger::onFirstRef()
416{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800417 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418}
419
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800420SurfaceFlinger::~SurfaceFlinger()
421{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422}
423
Dan Stozac7014012014-02-14 15:03:43 -0800424void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425{
426 // the window manager died on us. prepare its eulogy.
427
Andy McFadden13a082e2012-08-24 10:16:42 -0700428 // restore initial conditions (default device unblank, etc)
429 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430
431 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700432 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433}
434
Robert Carr1db73f62016-12-21 12:58:51 -0800435static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700436 status_t err = client->initCheck();
437 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800438 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800439 }
Robert Carr1db73f62016-12-21 12:58:51 -0800440 return nullptr;
441}
442
443sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
444 return initClient(new Client(this));
445}
446
447sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
448 const sp<IGraphicBufferProducer>& gbp) {
449 if (authenticateSurfaceTexture(gbp) == false) {
450 return nullptr;
451 }
452 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
453 if (layer == nullptr) {
454 return nullptr;
455 }
456
457 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800458}
459
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700460sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
461 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700462{
463 class DisplayToken : public BBinder {
464 sp<SurfaceFlinger> flinger;
465 virtual ~DisplayToken() {
466 // no more references, this display must be terminated
467 Mutex::Autolock _l(flinger->mStateLock);
468 flinger->mCurrentState.displays.removeItem(this);
469 flinger->setTransactionFlags(eDisplayTransactionNeeded);
470 }
471 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700472 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700473 : flinger(flinger) {
474 }
475 };
476
477 sp<BBinder> token = new DisplayToken(this);
478
479 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700480 DisplayDeviceState info;
481 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700482 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700483 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700484 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800485 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700486 return token;
487}
488
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700489void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700490 Mutex::Autolock _l(mStateLock);
491
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700492 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700493 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700494 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 return;
496 }
497
498 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700499 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700500 ALOGE("destroyDisplay called for non-virtual display");
501 return;
502 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700503 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 mCurrentState.displays.removeItemsAt(idx);
505 setTransactionFlags(eDisplayTransactionNeeded);
506}
507
Mathias Agopiane57f2922012-08-09 16:29:12 -0700508sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700509 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800511 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700512 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700513 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700514}
515
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800516void SurfaceFlinger::bootFinished()
517{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700518 if (mStartPropertySetThread->join() != NO_ERROR) {
519 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800520 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800521 const nsecs_t now = systemTime();
522 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000523 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700524
525 // wait patiently for the window manager death
526 const String16 name("window");
527 sp<IBinder> window(defaultServiceManager()->getService(name));
528 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700529 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700530 }
531
Steven Thomas050b2c82017-03-06 11:45:16 -0800532 if (mVrFlinger) {
533 mVrFlinger->OnBootFinished();
534 }
535
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700536 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700537 // formerly we would just kill the process, but we now ask it to exit so it
538 // can choose where to stop the animation.
539 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700540
541 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
542 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
543 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700544
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800545 postMessageAsync(new LambdaMessage([this] {
546 readPersistentProperties();
547 mBootStage = BootStage::FINISHED;
548 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800549}
550
Dan Stoza436ccf32018-06-21 12:10:12 -0700551uint32_t SurfaceFlinger::getNewTexture() {
552 {
553 std::lock_guard lock(mTexturePoolMutex);
554 if (!mTexturePool.empty()) {
555 uint32_t name = mTexturePool.back();
556 mTexturePool.pop_back();
557 ATRACE_INT("TexturePoolSize", mTexturePool.size());
558 return name;
559 }
560
561 // The pool was too small, so increase it for the future
562 ++mTexturePoolSize;
563 }
564
565 // The pool was empty, so we need to get a new texture name directly using a
566 // blocking call to the main thread
567 uint32_t name = 0;
568 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
569 return name;
570}
571
Mathias Agopian3f844832013-08-07 21:24:32 -0700572void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700573 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700574}
575
Wei Wangf9b05ee2017-07-19 20:59:39 -0700576// Do not call property_set on main thread which will be blocked by init
577// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700578void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700579 ALOGI( "SurfaceFlinger's main thread ready to run. "
580 "Initializing graphics H/W...");
581
Thierry Strudel2924d012017-08-14 15:19:37 -0700582 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900583
Steven Thomasb02664d2017-07-26 18:48:28 -0700584 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800585
Steven Thomasb02664d2017-07-26 18:48:28 -0700586 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700587 if (mUseScheduler) {
Lloyd Pique90c115d2018-09-18 21:39:42 -0700588 mScheduler = getFactory().createScheduler(
Ana Krulece588e312018-09-18 12:32:24 -0700589 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Ana Krulec98b5b242018-08-10 15:03:23 -0700590 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700591 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700592 [this] { resyncWithRateLimit(); },
593 impl::EventThread::InterceptVSyncsCallback());
594 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700595 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700596 [this] { resyncWithRateLimit(); },
597 [this](nsecs_t timestamp) {
598 mInterceptor->saveVSyncEvent(timestamp);
599 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800600
Ana Krulec98b5b242018-08-10 15:03:23 -0700601 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700602 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
603 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700604 } else {
605 mEventThreadSource =
606 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
607 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
608 mEventThread =
609 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
610 [this] { resyncWithRateLimit(); },
611 impl::EventThread::InterceptVSyncsCallback(),
612 "appEventThread");
613 mSfEventThreadSource =
614 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
615 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
616
617 mSFEventThread =
618 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
619 [this] { resyncWithRateLimit(); },
620 [this](nsecs_t timestamp) {
621 mInterceptor->saveVSyncEvent(timestamp);
622 },
623 "sfEventThread");
624 mEventQueue->setEventThread(mSFEventThread.get());
625 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
626 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800627
Steven Thomasb02664d2017-07-26 18:48:28 -0700628 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700629 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700630 renderEngineFeature |= (useColorManagement ?
631 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700632 renderEngineFeature |= (useContextPriority ?
633 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700634
635 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
636 getBE().mRenderEngine =
Peiyong Linf11f39b2018-09-05 14:37:41 -0700637 renderengine::RenderEngine::create(static_cast<int32_t>(compositionPixelFormat),
638 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800639 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700640
641 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
642 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700643 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700644 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800645 // Process any initial hotplug and resulting display changes.
646 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700647 const auto display = getDefaultDisplayDeviceLocked();
648 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
649 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
650 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800651
Lloyd Piquefcd86612017-12-14 17:15:36 -0800652 // make the default display GLContext current so that we can create textures
653 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700654 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800655
Steven Thomas050b2c82017-03-06 11:45:16 -0800656 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700657 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700658 // This callback is called from the vr flinger dispatch thread. We
659 // need to call signalTransaction(), which requires holding
660 // mStateLock when we're not on the main thread. Acquiring
661 // mStateLock from the vr flinger dispatch thread might trigger a
662 // deadlock in surface flinger (see b/66916578), so post a message
663 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700664 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700665 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
666 mVrFlingerRequestsDisplay = requestDisplay;
667 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700668 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800669 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700670 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
671 getHwComposer()
672 .getHwcDisplayId(display->getId())
673 .value_or(0),
674 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800675 if (!mVrFlinger) {
676 ALOGE("Failed to start vrflinger");
677 }
678 }
679
Lloyd Pique90c115d2018-09-18 21:39:42 -0700680 mEventControlThread = getFactory().createEventControlThread(
Lloyd Pique379adc12018-01-22 17:31:47 -0800681 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700682
Mathias Agopian92a979a2012-08-02 18:32:23 -0700683 // initialize our drawing state
684 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700685
Andy McFadden13a082e2012-08-24 10:16:42 -0700686 // set initial conditions (e.g. unblank default device)
687 initializeDisplays();
688
David Sodmanbc815282017-11-05 18:57:52 -0800689 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700690
Wei Wangf9b05ee2017-07-19 20:59:39 -0700691 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700692
693 const bool presentFenceReliable =
694 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
695 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700696
697 if (mStartPropertySetThread->Start() != NO_ERROR) {
698 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800699 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800700
Chia-I Wud49d6692018-06-27 07:17:41 +0800701 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
702 // is used to saturate legacy sRGB content. However, to make sure the same color under
703 // Display P3 will be saturated to the same color, we intentionally break the API spec
704 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
705 // such saturation matrix on Display P3 is understood fully, the API should always return
706 // identify matrix.
707 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
708 Dataspace::SRGB_LINEAR);
709
710 // we will apply this on Display P3.
711 if (mEnhancedSaturationMatrix != mat4()) {
712 ColorSpace srgb(ColorSpace::sRGB());
713 ColorSpace displayP3(ColorSpace::DisplayP3());
714 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
715 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
716 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
717 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800718
Dan Stoza9e56aa02015-11-02 13:00:03 -0800719 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700720}
721
Romain Guy11d63f42017-07-20 12:47:14 -0700722void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700723 Mutex::Autolock _l(mStateLock);
724
Romain Guy11d63f42017-07-20 12:47:14 -0700725 char value[PROPERTY_VALUE_MAX];
726
727 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800728 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700729 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800730 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100731
732 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700733 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700734}
735
Mathias Agopiana67e4182012-06-19 17:26:12 -0700736void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800737 // Start boot animation service by setting a property mailbox
738 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700739 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800740 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700741 if (mStartPropertySetThread->join() != NO_ERROR) {
742 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800743 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700744}
745
Mathias Agopian875d8e12013-06-07 15:35:48 -0700746size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800747 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700748}
749
Mathias Agopian875d8e12013-06-07 15:35:48 -0700750size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800751 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700752}
753
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800754// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800755
Jamie Gennis582270d2011-08-17 18:19:00 -0700756bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800757 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800758 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800759 return authenticateSurfaceTextureLocked(bufferProducer);
760}
761
762bool SurfaceFlinger::authenticateSurfaceTextureLocked(
763 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800764 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800765 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800766}
767
Brian Anderson6b376712017-04-04 10:51:39 -0700768status_t SurfaceFlinger::getSupportedFrameTimestamps(
769 std::vector<FrameEvent>* outSupported) const {
770 *outSupported = {
771 FrameEvent::REQUESTED_PRESENT,
772 FrameEvent::ACQUIRE,
773 FrameEvent::LATCH,
774 FrameEvent::FIRST_REFRESH_START,
775 FrameEvent::LAST_REFRESH_START,
776 FrameEvent::GPU_COMPOSITION_DONE,
777 FrameEvent::DEQUEUE_READY,
778 FrameEvent::RELEASE,
779 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700780 ConditionalLock _l(mStateLock,
781 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700782 if (!getHwComposer().hasCapability(
783 HWC2::Capability::PresentFenceIsNotReliable)) {
784 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
785 }
786 return NO_ERROR;
787}
788
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700789status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
790 Vector<DisplayInfo>* configs) {
791 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700792 return BAD_VALUE;
793 }
794
Jesse Hall692c7232012-11-08 15:41:56 -0800795 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700796 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
797 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700798 type = i;
799 break;
800 }
801 }
802
803 if (type < 0) {
804 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700805 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700806
Mathias Agopian8b736f12012-08-13 17:54:26 -0700807 // TODO: Not sure if display density should handled by SF any longer
808 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700809 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700810 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700811 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800812 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700813 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814 }
815 return density;
816 }
817 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700818 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700820 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 return getDensityFromProperty("ro.sf.lcd_density"); }
822 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700823
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700825
Steven Thomas6d8110b2017-08-31 18:24:21 -0700826 ConditionalLock _l(mStateLock,
827 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700829 DisplayInfo info = DisplayInfo();
830
Dan Stoza9e56aa02015-11-02 13:00:03 -0800831 float xdpi = hwConfig->getDpiX();
832 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700833
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700834 info.w = hwConfig->getWidth();
835 info.h = hwConfig->getHeight();
836 // Default display viewport to display width and height
837 info.viewportW = info.w;
838 info.viewportH = info.h;
839
Dan Stoza7f7da322014-05-02 15:26:25 -0700840 if (type == DisplayDevice::DISPLAY_PRIMARY) {
841 // The density of the device is provided by a build property
842 float density = Density::getBuildDensity() / 160.0f;
843 if (density == 0) {
844 // the build doesn't provide a density -- this is wrong!
845 // use xdpi instead
846 ALOGE("ro.sf.lcd_density must be defined as a build property");
847 density = xdpi / 160.0f;
848 }
849 if (Density::getEmuDensity()) {
850 // if "qemu.sf.lcd_density" is specified, it overrides everything
851 xdpi = ydpi = density = Density::getEmuDensity();
852 density /= 160.0f;
853 }
854 info.density = density;
855
856 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700857 const auto display = getDefaultDisplayDeviceLocked();
858 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700859
860 // This is for screenrecord
861 const Rect viewport = display->getViewport();
862 if (viewport.isValid()) {
863 info.viewportW = uint32_t(viewport.getWidth());
864 info.viewportH = uint32_t(viewport.getHeight());
865 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700866 } else {
867 // TODO: where should this value come from?
868 static const int TV_DENSITY = 213;
869 info.density = TV_DENSITY / 160.0f;
870 info.orientation = 0;
871 }
872
Dan Stoza7f7da322014-05-02 15:26:25 -0700873 info.xdpi = xdpi;
874 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800875 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900876 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800877
Andy McFadden91b2ca82014-06-13 14:04:23 -0700878 // This is how far in advance a buffer must be queued for
879 // presentation at a given time. If you want a buffer to appear
880 // on the screen at time N, you must submit the buffer before
881 // (N - presentationDeadline).
882 //
883 // Normally it's one full refresh period (to give SF a chance to
884 // latch the buffer), but this can be reduced by configuring a
885 // DispSync offset. Any additional delays introduced by the hardware
886 // composer or panel must be accounted for here.
887 //
888 // We add an additional 1ms to allow for processing time and
889 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800891 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700892
893 // All non-virtual displays are currently considered secure.
894 info.secure = true;
895
Iris Chang7501ed62018-04-30 14:45:42 +0800896 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700897 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800898 std::swap(info.w, info.h);
899 }
900
Michael Wright28f24d02016-07-12 13:30:53 -0700901 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700902 }
903
Dan Stoza7f7da322014-05-02 15:26:25 -0700904 return NO_ERROR;
905}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700906
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700907status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
908 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700909 return BAD_VALUE;
910 }
911
Ana Krulece588e312018-09-18 12:32:24 -0700912 // FIXME for now we always return stats for the primary display.
913 if (mUseScheduler) {
914 mScheduler->getDisplayStatInfo(stats);
915 } else {
916 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
917 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
918 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700919 return NO_ERROR;
920}
921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
923 const auto display = getDisplayDevice(displayToken);
924 if (!display) {
925 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800926 return BAD_VALUE;
927 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700928
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700929 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700930}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
933 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700934 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700935 return;
936 }
937
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700939 ALOGW("Trying to set config for virtual display");
940 return;
941 }
942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943 display->setActiveConfig(mode);
944 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700945}
946
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700948 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949 Vector<DisplayInfo> configs;
950 getDisplayConfigs(displayToken, &configs);
951 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
952 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
953 configs.size());
954 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700955 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700956 const auto display = getDisplayDevice(displayToken);
957 if (!display) {
958 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
959 displayToken.get());
960 } else if (display->isVirtual()) {
961 ALOGW("Attempt to set active config %d for virtual display", mode);
962 } else {
963 setActiveConfigInternal(display, mode);
964 }
965 }));
966
Mathias Agopian888c8222012-08-04 21:10:38 -0700967 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700968}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700969status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
970 Vector<ColorMode>* outColorModes) {
971 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700972 return BAD_VALUE;
973 }
974
Michael Wright28f24d02016-07-12 13:30:53 -0700975 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700976 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
977 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700978 type = i;
979 break;
980 }
981 }
982
983 if (type < 0) {
984 return type;
985 }
986
Peiyong Lina52f0292018-03-14 17:26:31 -0700987 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700988 {
989 ConditionalLock _l(mStateLock,
990 std::this_thread::get_id() != mMainThreadId);
991 modes = getHwComposer().getColorModes(type);
992 }
Michael Wright28f24d02016-07-12 13:30:53 -0700993 outColorModes->clear();
994 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
995
996 return NO_ERROR;
997}
998
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700999ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1000 if (const auto display = getDisplayDevice(displayToken)) {
1001 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001002 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001003 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001004}
1005
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001006void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1007 Dataspace dataSpace, RenderIntent renderIntent) {
1008 ColorMode currentMode = display->getActiveColorMode();
1009 Dataspace currentDataSpace = display->getCompositionDataSpace();
1010 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001011
Peiyong Lin38e9a562018-04-10 16:24:20 -07001012 if (mode == currentMode && dataSpace == currentDataSpace &&
1013 renderIntent == currentRenderIntent) {
1014 return;
1015 }
1016
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001017 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001018 ALOGW("Trying to set config for virtual display");
1019 return;
1020 }
1021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001022 display->setActiveColorMode(mode);
1023 display->setCompositionDataSpace(dataSpace);
1024 display->setActiveRenderIntent(renderIntent);
1025 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001026
1027 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001028 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1029 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001030}
1031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001033 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001034 Vector<ColorMode> modes;
1035 getDisplayColorModes(displayToken, &modes);
1036 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1037 if (mode < ColorMode::NATIVE || !exists) {
1038 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1039 decodeColorMode(mode).c_str(), mode, displayToken.get());
1040 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001041 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001042 const auto display = getDisplayDevice(displayToken);
1043 if (!display) {
1044 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1045 decodeColorMode(mode).c_str(), mode, displayToken.get());
1046 } else if (display->isVirtual()) {
1047 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1048 decodeColorMode(mode).c_str(), mode);
1049 } else {
1050 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1051 RenderIntent::COLORIMETRIC);
1052 }
1053 }));
1054
Michael Wright28f24d02016-07-12 13:30:53 -07001055 return NO_ERROR;
1056}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001057
Svetoslavd85084b2014-03-20 10:28:31 -07001058status_t SurfaceFlinger::clearAnimationFrameStats() {
1059 Mutex::Autolock _l(mStateLock);
1060 mAnimFrameTracker.clearStats();
1061 return NO_ERROR;
1062}
1063
1064status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1065 Mutex::Autolock _l(mStateLock);
1066 mAnimFrameTracker.getStats(outStats);
1067 return NO_ERROR;
1068}
1069
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001070status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1071 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001072 Mutex::Autolock _l(mStateLock);
1073
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001074 const auto display = getDisplayDeviceLocked(displayToken);
1075 if (!display) {
1076 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001077 return BAD_VALUE;
1078 }
1079
Peiyong Linfb069302018-04-25 14:34:31 -07001080 // At this point the DisplayDeivce should already be set up,
1081 // meaning the luminance information is already queried from
1082 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001083 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001084 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1085 capabilities.getDesiredMaxLuminance(),
1086 capabilities.getDesiredMaxAverageLuminance(),
1087 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001088
1089 return NO_ERROR;
1090}
1091
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001092status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001093 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001094 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001095
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 if (mInjectVSyncs == enable) {
1097 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001098 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001099
Ana Krulec98b5b242018-08-10 15:03:23 -07001100 // TODO(akrulec): Part of the Injector should be refactored, so that it
1101 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001102 if (enable) {
1103 ALOGV("VSync Injections enabled");
1104 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001105 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001106 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001107 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001108 impl::EventThread::InterceptVSyncsCallback(),
1109 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001110 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001111 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112 } else {
1113 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001114 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 }
1116
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001117 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001118 }));
1119
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001120 return NO_ERROR;
1121}
1122
1123status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001124 Mutex::Autolock _l(mStateLock);
1125
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001126 if (!mInjectVSyncs) {
1127 ALOGE("VSync Injections not enabled");
1128 return BAD_VALUE;
1129 }
1130 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1131 ALOGV("Injecting VSync inside SurfaceFlinger");
1132 mVSyncInjector->onInjectSyncEvent(when);
1133 }
1134 return NO_ERROR;
1135}
1136
Lloyd Pique755e3192018-01-31 16:46:15 -08001137status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1138 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001139 // Try to acquire a lock for 1s, fail gracefully
1140 const status_t err = mStateLock.timedLock(s2ns(1));
1141 const bool locked = (err == NO_ERROR);
1142 if (!locked) {
1143 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1144 return TIMED_OUT;
1145 }
1146
1147 outLayers->clear();
1148 mCurrentState.traverseInZOrder([&](Layer* layer) {
1149 outLayers->push_back(layer->getLayerDebugInfo());
1150 });
1151
1152 mStateLock.unlock();
1153 return NO_ERROR;
1154}
1155
Peiyong Lin0256f722018-08-31 15:45:10 -07001156status_t SurfaceFlinger::getCompositionPreference(Dataspace* outDataSpace,
1157 ui::PixelFormat* outPixelFormat) const {
1158 *outDataSpace = compositionDataSpace;
1159 *outPixelFormat = compositionPixelFormat;
1160 return NO_ERROR;
1161}
1162
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001163// ----------------------------------------------------------------------------
1164
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001165sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1166 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001167 if (mUseScheduler) {
1168 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1169 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1170 } else {
1171 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1172 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001173 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001174 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1175 return mSFEventThread->createEventConnection();
1176 } else {
1177 return mEventThread->createEventConnection();
1178 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001179 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001180}
1181
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001182// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001183
1184void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001185 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001186}
1187
1188void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001189 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001190}
1191
1192void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001193 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001194}
1195
1196void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001197 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001198 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001199}
1200
1201status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001202 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001203 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001204}
1205
1206status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001207 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001208 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001209 if (res == NO_ERROR) {
1210 msg->wait();
1211 }
1212 return res;
1213}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001214
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001215void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001216 do {
1217 waitForEvent();
1218 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001219}
1220
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221void SurfaceFlinger::enableHardwareVsync() {
1222 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001223 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001224 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001225 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001226 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001227 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228}
1229
Jesse Hall948fe0c2013-10-14 12:56:09 -07001230void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001231 Mutex::Autolock _l(mHWVsyncLock);
1232
Jesse Hall948fe0c2013-10-14 12:56:09 -07001233 if (makeAvailable) {
1234 mHWVsyncAvailable = true;
1235 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001236 // Hardware vsync is not currently available, so abort the resync
1237 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001238 return;
1239 }
1240
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001241 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1242 if (!getHwComposer().isConnected(displayId)) {
1243 return;
1244 }
1245
1246 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001247 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001248
Ana Krulece588e312018-09-18 12:32:24 -07001249 if (mUseScheduler) {
1250 mScheduler->setVsyncPeriod(period);
1251 } else {
1252 mPrimaryDispSync->reset();
1253 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254
Ana Krulece588e312018-09-18 12:32:24 -07001255 if (!mPrimaryHWVsyncEnabled) {
1256 mPrimaryDispSync->beginResync();
1257 mEventControlThread->setVsyncEnabled(true);
1258 mPrimaryHWVsyncEnabled = true;
1259 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001260 }
1261}
1262
Jesse Hall948fe0c2013-10-14 12:56:09 -07001263void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264 Mutex::Autolock _l(mHWVsyncLock);
1265 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001266 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001267 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001268 mPrimaryHWVsyncEnabled = false;
1269 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001270 if (makeUnavailable) {
1271 mHWVsyncAvailable = false;
1272 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273}
1274
Tim Murray4a4e4a22016-04-19 16:29:23 +00001275void SurfaceFlinger::resyncWithRateLimit() {
1276 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001277
1278 // No explicit locking is needed here since EventThread holds a lock while calling this method
1279 static nsecs_t sLastResyncAttempted = 0;
1280 const nsecs_t now = systemTime();
1281 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001282 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001283 }
Dan Stoza57164302017-05-08 14:03:54 -07001284 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001285}
1286
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001287void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1288 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001289 ATRACE_NAME("SF onVsync");
1290
Steven Thomas3cfac282017-02-06 12:29:30 -08001291 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001292 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001293 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001294 return;
1295 }
1296
1297 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001298 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001299 return;
1300 }
1301
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001302 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1303 // For now, we don't do anything with external display vsyncs.
1304 return;
1305 }
1306
Ana Krulece588e312018-09-18 12:32:24 -07001307 if (mUseScheduler) {
1308 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001309 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001310 bool needsHwVsync = false;
1311 { // Scope for the lock
1312 Mutex::Autolock _l(mHWVsyncLock);
1313 if (mPrimaryHWVsyncEnabled) {
1314 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1315 }
1316 }
1317
1318 if (needsHwVsync) {
1319 enableHardwareVsync();
1320 } else {
1321 disableHardwareVsync(false);
1322 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001323 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001324}
1325
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001326void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001327 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1328 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001329}
1330
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001331void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001332 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001333 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001334 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001335
Lloyd Piqueba04e622017-12-14 17:11:26 -08001336 // Ignore events that do not have the right sequenceId.
1337 if (sequenceId != getBE().mComposerSequenceId) {
1338 return;
1339 }
1340
Steven Thomasb02664d2017-07-26 18:48:28 -07001341 // Only lock if we're not on the main thread. This function is normally
1342 // called on a hwbinder thread, but for the primary display it's called on
1343 // the main thread with the state lock already held, so don't attempt to
1344 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001345 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001346
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001347 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001348
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001349 if (std::this_thread::get_id() == mMainThreadId) {
1350 // Process all pending hot plug events immediately if we are on the main thread.
1351 processDisplayHotplugEventsLocked();
1352 }
1353
Lloyd Piqueba04e622017-12-14 17:11:26 -08001354 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001355}
1356
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001357void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001358 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001359 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001361 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001362 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001363}
1364
Dan Stoza9e56aa02015-11-02 13:00:03 -08001365void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001366 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001368 getHwComposer().setVsyncEnabled(disp,
1369 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001370}
1371
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001372// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001373void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001374 if (mUseScheduler) {
1375 mScheduler->disableHardwareVsync(true);
1376 } else {
1377 disableHardwareVsync(true);
1378 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001379 // Clear the drawing state so that the logic inside of
1380 // handleTransactionLocked will fire. It will determine the delta between
1381 // mCurrentState and mDrawingState and re-apply all changes when we make the
1382 // transition.
1383 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001384 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001385 mDisplays.clear();
1386}
1387
Steven Thomas050b2c82017-03-06 11:45:16 -08001388void SurfaceFlinger::updateVrFlinger() {
1389 if (!mVrFlinger)
1390 return;
1391 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001392 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001393 return;
1394 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001395
David Sodman105b7dc2017-11-04 20:28:14 -07001396 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001397 ALOGE("Vr flinger is only supported for remote hardware composer"
1398 " service connections. Ignoring request to transition to vr"
1399 " flinger.");
1400 mVrFlingerRequestsDisplay = false;
1401 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001402 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001403
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001404 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001405
Steven Thomas0123ac62018-07-12 11:32:34 -07001406 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001407 LOG_ALWAYS_FATAL_IF(!display);
1408 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001409 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1410 // called below. Clear the reference now so we don't accidentally use it
1411 // later.
1412 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001413
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001415 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001417
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001419 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001420 getBE().mHwc = getFactory().createHWComposer(
1421 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001422 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001423
David Sodman105b7dc2017-11-04 20:28:14 -07001424 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1425 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001426
1427 if (vrFlingerRequestsDisplay) {
1428 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001429 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430
1431 mVisibleRegionsDirty = true;
1432 invalidateHwcGeometry();
1433
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001434 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001435 display = getDefaultDisplayDeviceLocked();
1436 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001437 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001438
Steven Thomasb02664d2017-07-26 18:48:28 -07001439 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001440 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001441 const nsecs_t period = activeConfig->getVsyncPeriod();
1442 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001443
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001444 // The present fences returned from vr_hwc are not an accurate
1445 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001446 if (mUseScheduler) {
1447 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1448 } else {
1449 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1450 !hasSyncFramework);
1451 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001452
Steven Thomasb02664d2017-07-26 18:48:28 -07001453 // Use phase of 0 since phase is not known.
1454 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001455 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1456 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001457
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001458 resyncToHardwareVsync(false);
1459
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001460 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001461 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001462}
1463
Mathias Agopian4fec8732012-06-29 14:12:52 -07001464void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001465 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001466 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001467 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001468 bool frameMissed = !mHadClientComposition &&
1469 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001470 (mPreviousPresentFence->getSignalTime() ==
1471 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001472 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001473 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001474 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001475 mTimeStats.incrementMissedFrames();
1476 if (mPropagateBackpressure) {
1477 signalLayerUpdate();
1478 break;
1479 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001480 }
Dan Stoza50182882016-07-08 12:02:20 -07001481
Steven Thomas050b2c82017-03-06 11:45:16 -08001482 // Now that we're going to make it to the handleMessageTransaction()
1483 // call below it's safe to call updateVrFlinger(), which will
1484 // potentially trigger a display handoff.
1485 updateVrFlinger();
1486
Dan Stoza6b9454d2014-11-07 16:00:59 -08001487 bool refreshNeeded = handleMessageTransaction();
1488 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001489 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001490 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001491 // Signal a refresh if a transaction modified the window state,
1492 // a new buffer was latched, or if HWC has requested a full
1493 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001494 signalRefresh();
1495 }
1496 break;
1497 }
1498 case MessageQueue::REFRESH: {
1499 handleMessageRefresh();
1500 break;
1501 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001502 }
1503}
1504
Dan Stoza6b9454d2014-11-07 16:00:59 -08001505bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001506 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001507 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001508 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001509 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001510 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001512}
1513
Mathias Agopian4fec8732012-06-29 14:12:52 -07001514void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001515 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001516
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001517 mRefreshPending = false;
1518
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001519 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001520 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001521 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001522 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001523 for (const auto& [token, display] : mDisplays) {
1524 beginFrame(display);
1525 prepareFrame(display);
1526 doDebugFlashRegions(display, repaintEverything);
1527 doComposition(display, repaintEverything);
1528 }
1529
Adrian Roos1e1a1282017-11-01 19:05:31 +01001530 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001531 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001532
1533 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001534 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001535
Dan Stozabfbffeb2016-07-21 14:49:33 -07001536 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001537 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001538 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001539 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001540 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001541
Alec Mouri86770e52018-09-24 22:40:58 +00001542 // Setup RenderEngine sync fences if native sync is supported.
1543 if (getBE().mRenderEngine->useNativeFenceSync()) {
1544 if (mHadClientComposition) {
1545 base::unique_fd flushFence(getRenderEngine().flush());
1546 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1547 getBE().flushFence = new Fence(std::move(flushFence));
1548 } else {
1549 // Cleanup for hygiene.
1550 getBE().flushFence = Fence::NO_FENCE;
1551 }
1552 }
1553
Jorim Jaggi90535212018-05-23 23:44:06 +02001554 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001555
David Sodman7e4ae112018-02-09 15:02:28 -08001556 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001557 for (const auto& [token, display] : mDisplays) {
1558 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001559 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001560 compositionInfo.hwc.hwcLayer = nullptr;
1561 }
David Sodmanba340492018-08-05 21:51:33 -07001562 }
David Sodman7e4ae112018-02-09 15:02:28 -08001563
1564 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001565}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001566
David Sodmanfa9b2af2017-12-24 13:28:59 -08001567
1568bool SurfaceFlinger::handleMessageInvalidate() {
1569 ATRACE_CALL();
1570 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001571}
1572
David Sodman79bba0e2018-08-05 18:07:49 -07001573void SurfaceFlinger::calculateWorkingSet() {
1574 ATRACE_CALL();
1575 ALOGV(__FUNCTION__);
1576
David Sodman79bba0e2018-08-05 18:07:49 -07001577 // build the h/w work list
1578 if (CC_UNLIKELY(mGeometryInvalid)) {
1579 mGeometryInvalid = false;
1580 for (const auto& [token, display] : mDisplays) {
1581 const auto displayId = display->getId();
1582 if (displayId >= 0) {
1583 const Vector<sp<Layer>>& currentLayers(
1584 display->getVisibleLayersSortedByZ());
1585 for (size_t i = 0; i < currentLayers.size(); i++) {
1586 const auto& layer = currentLayers[i];
1587
1588 if (!layer->hasHwcLayer(displayId)) {
1589 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1590 layer->forceClientComposition(displayId);
1591 continue;
1592 }
1593 }
1594
1595 layer->setGeometry(display, i);
1596 if (mDebugDisableHWC || mDebugRegion) {
1597 layer->forceClientComposition(displayId);
1598 }
1599 }
1600 }
1601 }
1602 }
1603
1604 // Set the per-frame data
1605 for (const auto& [token, display] : mDisplays) {
1606 const auto displayId = display->getId();
1607 if (displayId < 0) {
1608 continue;
1609 }
1610
1611 if (mDrawingState.colorMatrixChanged) {
1612 display->setColorTransform(mDrawingState.colorMatrix);
1613 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1614 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1615 "display %d: %d", displayId, result);
1616 }
1617 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1618 if (layer->isHdrY410()) {
1619 layer->forceClientComposition(displayId);
1620 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1621 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1622 !display->hasHDR10Support()) {
1623 layer->forceClientComposition(displayId);
1624 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1625 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1626 !display->hasHLGSupport()) {
1627 layer->forceClientComposition(displayId);
1628 }
1629
Peiyong Lind3788632018-09-18 16:01:31 -07001630 // TODO(b/111562338) remove when composer 2.3 is shipped.
1631 if (layer->hasColorTransform()) {
1632 layer->forceClientComposition(displayId);
1633 }
1634
David Sodman79bba0e2018-08-05 18:07:49 -07001635 if (layer->getForceClientComposition(displayId)) {
1636 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1637 layer->setCompositionType(displayId, HWC2::Composition::Client);
1638 continue;
1639 }
1640
1641 layer->setPerFrameData(display);
1642 }
1643
Peiyong Lin13effd12018-07-24 17:01:47 -07001644 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001645 ColorMode colorMode;
1646 Dataspace dataSpace;
1647 RenderIntent renderIntent;
1648 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1649 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1650 }
1651 }
1652
1653 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001654
1655 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001656 const auto displayId = display->getId();
1657 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001658 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1659 auto displayId = display->getId();
1660 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1661 if (!layer->setHwcLayer(displayId)) {
1662 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1663 }
David Sodman15fb96e2018-01-07 10:23:24 -08001664 layer->getBE().compositionInfo.hwc.displayId = displayId;
1665 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001666 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1667 }
1668 }
David Sodman79bba0e2018-08-05 18:07:49 -07001669}
1670
David Sodmanfa9b2af2017-12-24 13:28:59 -08001671void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001672{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001673 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001674 // is debugging enabled
1675 if (CC_LIKELY(!mDebugRegion))
1676 return;
1677
David Sodmanfa9b2af2017-12-24 13:28:59 -08001678 if (display->isPoweredOn()) {
1679 // transform the dirty region into this screen's coordinate space
1680 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1681 if (!dirtyRegion.isEmpty()) {
1682 // redraw the whole screen
1683 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001684
David Sodmanfa9b2af2017-12-24 13:28:59 -08001685 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001686 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001687 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001688
David Sodmanfa9b2af2017-12-24 13:28:59 -08001689 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001690 }
1691 }
1692
David Sodmanfa9b2af2017-12-24 13:28:59 -08001693 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001694
1695 if (mDebugRegion > 1) {
1696 usleep(mDebugRegion * 1000);
1697 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001698
David Sodmanfa9b2af2017-12-24 13:28:59 -08001699 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001700 status_t result = display->prepareFrame(
1701 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001702 ALOGE_IF(result != NO_ERROR,
1703 "prepareFrame for display %d failed:"
1704 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001705 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001706 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001707}
1708
Adrian Roos1e1a1282017-11-01 19:05:31 +01001709void SurfaceFlinger::doTracing(const char* where) {
1710 ATRACE_CALL();
1711 ATRACE_NAME(where);
1712 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001713 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001714 }
1715}
1716
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001717void SurfaceFlinger::logLayerStats() {
1718 ATRACE_CALL();
1719 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001720 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001721 if (display->isPrimary()) {
1722 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001723 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001724 }
1725 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001726
1727 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001728 }
1729}
1730
David Sodman2b406362017-12-15 13:33:47 -08001731void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001732{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001733 ATRACE_CALL();
1734 ALOGV("preComposition");
1735
David Sodman2b406362017-12-15 13:33:47 -08001736 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1737
Mathias Agopiancd60f992012-08-16 16:28:27 -07001738 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001739 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001740 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001741 needExtraInvalidate = true;
1742 }
Robert Carr2047fae2016-11-28 14:09:09 -08001743 });
1744
Mathias Agopiancd60f992012-08-16 16:28:27 -07001745 if (needExtraInvalidate) {
1746 signalLayerUpdate();
1747 }
1748}
1749
Ana Krulece588e312018-09-18 12:32:24 -07001750void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1751 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001752 // Update queue of past composite+present times and determine the
1753 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001754 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001755 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001756 while (!getBE().mCompositePresentTimes.empty()) {
1757 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001758 // Cached values should have been updated before calling this method,
1759 // which helps avoid duplicate syscalls.
1760 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1761 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1762 break;
1763 }
1764 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001765 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001766 }
1767
1768 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001769 while (getBE().mCompositePresentTimes.size() > 16) {
1770 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001771 }
1772
Ana Krulece588e312018-09-18 12:32:24 -07001773 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001774}
1775
Ana Krulece588e312018-09-18 12:32:24 -07001776void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1777 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001778 // Integer division and modulo round toward 0 not -inf, so we need to
1779 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001780 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1781 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1782 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001783
Brian Andersond0010582017-03-07 13:20:31 -08001784 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1785 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001786 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001787 }
1788
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001789 // Snap the latency to a value that removes scheduling jitter from the
1790 // composition and present times, which often have >1ms of jitter.
1791 // Reducing jitter is important if an app attempts to extrapolate
1792 // something (such as user input) to an accurate diasplay time.
1793 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1794 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001795 nsecs_t bias = stats.vsyncPeriod / 2;
1796 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1797 nsecs_t snappedCompositeToPresentLatency =
1798 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001799
David Sodman99974d22017-11-28 12:04:33 -08001800 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001801 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1802 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001803 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001804}
1805
David Sodman2b406362017-12-15 13:33:47 -08001806void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001807{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001808 ATRACE_CALL();
1809 ALOGV("postComposition");
1810
Brian Anderson3546a3f2016-07-14 11:51:14 -07001811 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001812 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001813 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001814 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001815 }
1816
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001817 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001818 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001819
David Sodman73beded2017-11-15 11:56:06 -08001820 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001821 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001822 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001823 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001824 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001825 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001826 } else {
1827 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1828 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001829
David Sodman73beded2017-11-15 11:56:06 -08001830 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001831 mPreviousPresentFence =
1832 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1833 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001834 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001835
Ana Krulece588e312018-09-18 12:32:24 -07001836 DisplayStatInfo stats;
1837 if (mUseScheduler) {
1838 mScheduler->getDisplayStatInfo(&stats);
1839 } else {
1840 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1841 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1842 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001843
David Sodman2b406362017-12-15 13:33:47 -08001844 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001845 // when we started doing work for this frame, but that should be okay
1846 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001847 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001848 CompositorTiming compositorTiming;
1849 {
David Sodman99974d22017-11-28 12:04:33 -08001850 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1851 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001852 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001853
Robert Carr2047fae2016-11-28 14:09:09 -08001854 mDrawingState.traverseInZOrder([&](Layer* layer) {
1855 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001856 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001857 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001858 recordBufferingStats(layer->getName().string(),
1859 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001860 }
Robert Carr2047fae2016-11-28 14:09:09 -08001861 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001862
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001863 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001864 if (mUseScheduler) {
1865 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001866 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001867 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1868 enableHardwareVsync();
1869 } else {
1870 disableHardwareVsync(false);
1871 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001872 }
1873 }
1874
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001875 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001876 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001877 if (mUseScheduler) {
1878 mScheduler->enableHardwareVsync();
1879 } else {
1880 enableHardwareVsync();
1881 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001882 }
1883 }
1884
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001885 if (mAnimCompositionPending) {
1886 mAnimCompositionPending = false;
1887
Brian Anderson4e606e32017-03-16 15:34:57 -07001888 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001889 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001890 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001891 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001892 // The HWC doesn't support present fences, so use the refresh
1893 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001894 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001895 mAnimFrameTracker.setActualPresentTime(presentTime);
1896 }
1897 mAnimFrameTracker.advanceFrame();
1898 }
Dan Stozab90cf072015-03-05 11:05:59 -08001899
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001900 mTimeStats.incrementTotalFrames();
1901 if (mHadClientComposition) {
1902 mTimeStats.incrementClientCompositionFrames();
1903 }
1904
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001905 mTimeStats.setPresentFenceGlobal(presentFenceTime);
1906
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001907 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001908 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001909 return;
1910 }
1911
1912 nsecs_t currentTime = systemTime();
1913 if (mHasPoweredOff) {
1914 mHasPoweredOff = false;
1915 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001916 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001917 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001918 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1919 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001920 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001921 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001922 }
David Sodman4a36e932017-11-07 14:29:47 -08001923 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001924 }
David Sodman4a36e932017-11-07 14:29:47 -08001925 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001926
1927 {
1928 std::lock_guard lock(mTexturePoolMutex);
1929 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1930 if (refillCount > 0) {
1931 const size_t offset = mTexturePool.size();
1932 mTexturePool.resize(mTexturePoolSize);
1933 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1934 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1935 }
1936 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001937}
1938
1939void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 ATRACE_CALL();
1941 ALOGV("rebuildLayerStacks");
1942
Mathias Agopiancd60f992012-08-16 16:28:27 -07001943 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001944 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001945 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001946 mVisibleRegionsDirty = false;
1947 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001948
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001949 for (const auto& pair : mDisplays) {
1950 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001951 Region opaqueRegion;
1952 Region dirtyRegion;
1953 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001954 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001955 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001956 const Rect bounds = display->getBounds();
1957 if (display->isPoweredOn()) {
1958 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001959
Jeff Sharkey76488112017-02-27 14:15:18 -07001960 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001961 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001962 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001963 Region drawRegion(tr.transform(
1964 layer->visibleNonTransparentRegion));
1965 drawRegion.andSelf(bounds);
1966 if (!drawRegion.isEmpty()) {
1967 layersSortedByZ.add(layer);
1968 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001969 // Clear out the HWC layer if this layer was
1970 // previously visible, but no longer is
1971 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001972 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001973 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001974 // WM changes display->layerStack upon sleep/awake.
1975 // Here we make sure we delete the HWC layers even if
1976 // WM changed their layer stack.
1977 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001978 }
1979
1980 // If a layer is not going to get a release fence because
1981 // it is invisible, but it is also going to release its
1982 // old buffer, add it to the list of layers needing
1983 // fences.
1984 if (hwcLayerDestroyed) {
1985 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1986 mLayersWithQueuedFrames.cend(), layer);
1987 if (found != mLayersWithQueuedFrames.cend()) {
1988 layersNeedingFences.add(layer);
1989 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001990 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001991 });
1992 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001993 display->setVisibleLayersSortedByZ(layersSortedByZ);
1994 display->setLayersNeedingFences(layersNeedingFences);
1995 display->undefinedRegion.set(bounds);
1996 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1997 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001998 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001999 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002000}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002001
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002002// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002003// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002004// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002005// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002006// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002007// The returned HDR data space is one of
2008// - Dataspace::UNKNOWN
2009// - Dataspace::BT2020_HLG
2010// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002011Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2012 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002013 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002014 *outHdrDataSpace = Dataspace::UNKNOWN;
2015
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002016 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002017 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002018 case Dataspace::V0_SCRGB:
2019 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002020 case Dataspace::BT2020:
2021 case Dataspace::BT2020_ITU:
2022 case Dataspace::BT2020_LINEAR:
2023 case Dataspace::DISPLAY_BT2020:
2024 bestDataSpace = Dataspace::DISPLAY_BT2020;
2025 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002026 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002027 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002028 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002029 case Dataspace::BT2020_PQ:
2030 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002031 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002032 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002033 case Dataspace::BT2020_HLG:
2034 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002035 // When there's mixed PQ content and HLG content, we set the HDR
2036 // data space to be BT2020_PQ and convert HLG to PQ.
2037 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2038 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002039 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002040 break;
2041 default:
2042 break;
2043 }
Romain Guy54f154a2017-10-24 21:40:32 +01002044 }
2045
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002046 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002047}
2048
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002049// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002050void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2051 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002052 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2053 *outMode = ColorMode::NATIVE;
2054 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002055 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002056 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002057 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002058
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002059 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002060 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002061
Peiyong Lindfde5112018-06-05 10:58:41 -07002062 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002063 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002064 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002065 if (isHdr) {
2066 bestDataSpace = hdrDataSpace;
2067 }
2068
Chia-I Wu0d711262018-05-21 15:19:35 -07002069 RenderIntent intent;
2070 switch (mDisplayColorSetting) {
2071 case DisplayColorSetting::MANAGED:
2072 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002073 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002074 break;
2075 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002076 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002077 break;
2078 default: // vendor display color setting
2079 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2080 break;
2081 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002082
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002083 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002084}
2085
David Sodmanfa9b2af2017-12-24 13:28:59 -08002086void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002087{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002088 bool dirty = !display->getDirtyRegion(false).isEmpty();
2089 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2090 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002091
David Sodmanfa9b2af2017-12-24 13:28:59 -08002092 // If nothing has changed (!dirty), don't recompose.
2093 // If something changed, but we don't currently have any visible layers,
2094 // and didn't when we last did a composition, then skip it this time.
2095 // The second rule does two things:
2096 // - When all layers are removed from a display, we'll emit one black
2097 // frame, then nothing more until we get new layers.
2098 // - When a display is created with a private layer stack, we won't
2099 // emit any black frames until a layer is added to the layer stack.
2100 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002101
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002102 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2103 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002104 mustRecompose ? "doing" : "skipping",
2105 dirty ? "+" : "-",
2106 empty ? "+" : "-",
2107 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002108
David Sodmanfa9b2af2017-12-24 13:28:59 -08002109 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002110
David Sodmanfa9b2af2017-12-24 13:28:59 -08002111 if (mustRecompose) {
2112 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002113 }
2114}
2115
David Sodmanfa9b2af2017-12-24 13:28:59 -08002116void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002117{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002118 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002119 if (!display->isPoweredOn()) {
2120 return;
David Sodman2b406362017-12-15 13:33:47 -08002121 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002122
David Sodmanfb95bcc2017-12-22 15:45:30 -08002123 status_t result = display->prepareFrame(
2124 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002125 ALOGE_IF(result != NO_ERROR,
2126 "prepareFrame for display %d failed:"
2127 " %d (%s)",
2128 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002129}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002130
David Sodmanfa9b2af2017-12-24 13:28:59 -08002131void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002132 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002133 ALOGV("doComposition");
2134
David Sodmanfa9b2af2017-12-24 13:28:59 -08002135 if (display->isPoweredOn()) {
2136 // transform the dirty region into this screen's coordinate space
2137 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002138
David Sodmanfa9b2af2017-12-24 13:28:59 -08002139 // repaint the framebuffer (if needed)
2140 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002141
David Sodmanfa9b2af2017-12-24 13:28:59 -08002142 display->dirtyRegion.clear();
2143 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002144 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002145 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002146}
2147
David Sodmanfa9b2af2017-12-24 13:28:59 -08002148void SurfaceFlinger::postFrame()
2149{
2150 // |mStateLock| not needed as we are on the main thread
2151 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2152 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2153 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2154 logFrameStats();
2155 }
2156 }
2157}
2158
2159void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002160{
Mathias Agopian841cde52012-03-01 15:44:37 -08002161 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002162 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002163
David Sodmanfa9b2af2017-12-24 13:28:59 -08002164 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002165
David Sodmanfa9b2af2017-12-24 13:28:59 -08002166 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002167 const auto displayId = display->getId();
2168 if (displayId >= 0) {
2169 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002170 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002171 display->onSwapBuffersCompleted();
2172 display->makeCurrent();
David Sodman15094112018-10-11 09:39:37 -07002173 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002174 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002175
Chia-I Wu7b549592017-11-15 09:14:57 -08002176 // The layer buffer from the previous frame (if any) is released
2177 // by HWC only when the release fence from this frame (if any) is
2178 // signaled. Always get the release fence from HWC first.
David Sodman15094112018-10-11 09:39:37 -07002179 auto hwcLayer = layer->getHwcLayer(displayId);
2180 if (displayId >= 0) {
2181 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002182 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002183
2184 // If the layer was client composited in the previous frame, we
2185 // need to merge with the previous client target acquire fence.
2186 // Since we do not track that, always merge with the current
2187 // client target acquire fence when it is available, even though
2188 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002189 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002190 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002191 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002192 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002193
David Sodman15094112018-10-11 09:39:37 -07002194 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195 }
Chia-I Wu83806892017-11-16 10:50:20 -08002196
2197 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002198 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002199 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002200 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002201 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002202 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002203 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002204 }
2205 }
2206
Dominik Laskowski7e045462018-05-30 13:02:02 -07002207 if (displayId >= 0) {
2208 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002209 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002210 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002211}
2212
Mathias Agopian87baae12012-07-31 12:38:26 -07002213void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002214{
Mathias Agopian841cde52012-03-01 15:44:37 -08002215 ATRACE_CALL();
2216
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002217 // here we keep a copy of the drawing state (that is the state that's
2218 // going to be overwritten by handleTransactionLocked()) outside of
2219 // mStateLock so that the side-effects of the State assignment
2220 // don't happen with mStateLock held (which can cause deadlocks).
2221 State drawingState(mDrawingState);
2222
Mathias Agopianca4d3602011-05-19 15:38:14 -07002223 Mutex::Autolock _l(mStateLock);
2224 const nsecs_t now = systemTime();
2225 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002226
Mathias Agopianca4d3602011-05-19 15:38:14 -07002227 // Here we're guaranteed that some transaction flags are set
2228 // so we can call handleTransactionLocked() unconditionally.
2229 // We call getTransactionFlags(), which will also clear the flags,
2230 // with mStateLock held to guarantee that mCurrentState won't change
2231 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002232
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002233 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002234 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002235 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002236
Mathias Agopianca4d3602011-05-19 15:38:14 -07002237 mLastTransactionTime = systemTime() - now;
2238 mDebugInTransaction = 0;
2239 invalidateHwcGeometry();
2240 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002241}
2242
Dominik Laskowski7e045462018-05-30 13:02:02 -07002243DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002244 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002245 // Figure out whether the event is for the primary display or an
2246 // external display by matching the Hwc display id against one for a
2247 // connected display. If we did not find a match, we then check what
2248 // displays are not already connected to determine the type. If we don't
2249 // have a connected primary display, we assume the new display is meant to
2250 // be the primary display, and then if we don't have an external display,
2251 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002252 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2253 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002254 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002255 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002256 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002257 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002258 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002259 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002260 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002261 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002262 return DisplayDevice::DISPLAY_EXTERNAL;
2263 }
2264
2265 return DisplayDevice::DISPLAY_ID_INVALID;
2266}
2267
Lloyd Piqueba04e622017-12-14 17:11:26 -08002268void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2269 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002270 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002271 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002272 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002273 continue;
2274 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002275
2276 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2277 ALOGE("External displays are not supported by the vr hardware composer.");
2278 continue;
2279 }
2280
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002281 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002282 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002283 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002284 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002285 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002286
2287 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002288 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002289 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002290 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002291 DisplayDeviceState info;
2292 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002293 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2294 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002295 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002296 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002297 mInterceptor->saveDisplayCreation(info);
2298 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002299 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002300 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002301
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002302 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002303 if (idx >= 0) {
2304 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002305 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002306 mCurrentState.displays.removeItemsAt(idx);
2307 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002308 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002309 }
2310
2311 processDisplayChangesLocked();
2312 }
2313
2314 mPendingHotplugEvents.clear();
2315}
2316
Lloyd Pique99d3da52018-01-22 17:48:03 -08002317sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002318 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002319 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002320 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2321 creationArgs.isSecure = state.isSecure;
2322 creationArgs.displaySurface = dispSurface;
2323 creationArgs.hasWideColorGamut = false;
2324 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002325
Peiyong Lin13effd12018-07-24 17:01:47 -07002326 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002327 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002328 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002329 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002330 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002331 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002332
Dominik Laskowski7e045462018-05-30 13:02:02 -07002333 std::vector<RenderIntent> renderIntents =
2334 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002335 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002336 }
tangrobin6753a022018-08-10 10:58:54 +08002337 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002338
tangrobin6753a022018-08-10 10:58:54 +08002339 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002340 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2341 creationArgs.supportedPerFrameMetadata =
2342 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002343 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002344
Lloyd Pique90c115d2018-09-18 21:39:42 -07002345 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002346 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002347 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002348
2349 /*
2350 * Create our display's surface
2351 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002352 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002353 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002354 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002355 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002356 creationArgs.displayWidth = renderSurface->getWidth();
2357 creationArgs.displayHeight = renderSurface->getHeight();
2358 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002359
2360 // Make sure that composition can never be stalled by a virtual display
2361 // consumer that isn't processing buffers fast enough. We have to do this
2362 // in two places:
2363 // * Here, in case the display is composed entirely by HWC.
2364 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2365 // window's swap interval in eglMakeCurrent, so they'll override the
2366 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002367 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002368 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2369 }
2370
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002371 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2372 ? primaryDisplayOrientation
2373 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002374
Lloyd Pique99d3da52018-01-22 17:48:03 -08002375 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002376 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002377
Lloyd Pique90c115d2018-09-18 21:39:42 -07002378 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002379
2380 if (maxFrameBufferAcquiredBuffers >= 3) {
2381 nativeWindowSurface->preallocateBuffers();
2382 }
2383
2384 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002385 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002386 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002387 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002388 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002389 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002390 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002391 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002392 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002393 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002394 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002395 display->setLayerStack(state.layerStack);
2396 display->setProjection(state.orientation, state.viewport, state.frame);
2397 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002398
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002399 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002400}
2401
Lloyd Pique347200f2017-12-14 17:00:15 -08002402void SurfaceFlinger::processDisplayChangesLocked() {
2403 // here we take advantage of Vector's copy-on-write semantics to
2404 // improve performance by skipping the transaction entirely when
2405 // know that the lists are identical
2406 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2407 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2408 if (!curr.isIdenticalTo(draw)) {
2409 mVisibleRegionsDirty = true;
2410 const size_t cc = curr.size();
2411 size_t dc = draw.size();
2412
2413 // find the displays that were removed
2414 // (ie: in drawing state but not in current state)
2415 // also handle displays that changed
2416 // (ie: displays that are in both lists)
2417 for (size_t i = 0; i < dc;) {
2418 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2419 if (j < 0) {
2420 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002421 // Call makeCurrent() on the primary display so we can
2422 // be sure that nothing associated with this display
2423 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002424 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2425 defaultDisplay->makeCurrent();
2426 }
2427 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2428 display->disconnect(getHwComposer());
2429 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002430 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002431 if (mUseScheduler) {
2432 mScheduler->hotplugReceived(mAppConnectionHandle,
2433 EventThread::DisplayType::Primary, false);
2434 } else {
2435 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2436 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002437 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002438 if (mUseScheduler) {
2439 mScheduler->hotplugReceived(mAppConnectionHandle,
2440 EventThread::DisplayType::External, false);
2441 } else {
2442 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2443 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002444 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002445 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002446 } else {
2447 // this display is in both lists. see if something changed.
2448 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002449 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002450 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2451 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2452 if (state_binder != draw_binder) {
2453 // changing the surface is like destroying and
2454 // recreating the DisplayDevice, so we just remove it
2455 // from the drawing state, so that it get re-added
2456 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002457 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2458 display->disconnect(getHwComposer());
2459 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002460 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002461 mDrawingState.displays.removeItemsAt(i);
2462 dc--;
2463 // at this point we must loop to the next item
2464 continue;
2465 }
2466
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002467 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002468 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002469 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002470 }
2471 if ((state.orientation != draw[i].orientation) ||
2472 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002473 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002474 }
2475 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002476 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002477 }
2478 }
2479 }
2480 ++i;
2481 }
2482
2483 // find displays that were added
2484 // (ie: in current state but not in drawing state)
2485 for (size_t i = 0; i < cc; i++) {
2486 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2487 const DisplayDeviceState& state(curr[i]);
2488
2489 sp<DisplaySurface> dispSurface;
2490 sp<IGraphicBufferProducer> producer;
2491 sp<IGraphicBufferProducer> bqProducer;
2492 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002493 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002494
Dominik Laskowski7e045462018-05-30 13:02:02 -07002495 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002496 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002497 // Virtual displays without a surface are dormant:
2498 // they have external state (layer stack, projection,
2499 // etc.) but no internal state (i.e. a DisplayDevice).
2500 if (state.surface != nullptr) {
2501 // Allow VR composer to use virtual displays.
2502 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2503 int width = 0;
2504 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2505 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2506 int height = 0;
2507 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2508 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2509 int intFormat = 0;
2510 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2511 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002512 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002513
Dominik Laskowski7e045462018-05-30 13:02:02 -07002514 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2515 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002516 }
2517
2518 // TODO: Plumb requested format back up to consumer
2519
2520 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002521 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002522 bqProducer, bqConsumer,
2523 state.displayName);
2524
2525 dispSurface = vds;
2526 producer = vds;
2527 }
2528 } else {
2529 ALOGE_IF(state.surface != nullptr,
2530 "adding a supported display, but rendering "
2531 "surface is provided (%p), ignoring it",
2532 state.surface.get());
2533
Dominik Laskowski7e045462018-05-30 13:02:02 -07002534 displayId = state.type;
2535 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002536 producer = bqProducer;
2537 }
2538
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002539 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002540 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002541 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002542 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002543 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002544 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002545 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002546 if (mUseScheduler) {
2547 mScheduler->hotplugReceived(mAppConnectionHandle,
2548 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002549 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002550 } else {
2551 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2552 true);
2553 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002554 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002555 if (mUseScheduler) {
2556 mScheduler->hotplugReceived(mAppConnectionHandle,
2557 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002558 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002559 } else {
2560 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2561 true);
2562 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002563 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002564 }
2565 }
2566 }
2567 }
2568 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002569
2570 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002571}
2572
Mathias Agopian87baae12012-07-31 12:38:26 -07002573void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002574{
Dan Stoza7dde5992015-05-22 09:51:44 -07002575 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002576 mCurrentState.traverseInZOrder([](Layer* layer) {
2577 layer->notifyAvailableFrames();
2578 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002579
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580 /*
2581 * Traversal of the children
2582 * (perform the transaction for each of them if needed)
2583 */
2584
Mathias Agopian3559b072012-08-15 13:46:03 -07002585 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002586 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002588 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589
2590 const uint32_t flags = layer->doTransaction(0);
2591 if (flags & Layer::eVisibleRegion)
2592 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002593 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002594 }
2595
2596 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002597 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598 */
2599
Mathias Agopiane57f2922012-08-09 16:29:12 -07002600 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002601 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002602 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002603 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002605 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002606 // The transform hint might have changed for some layers
2607 // (either because a display has changed, or because a layer
2608 // as changed).
2609 //
2610 // Walk through all the layers in currentLayers,
2611 // and update their transform hint.
2612 //
2613 // If a layer is visible only on a single display, then that
2614 // display is used to calculate the hint, otherwise we use the
2615 // default display.
2616 //
2617 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2618 // the hint is set before we acquire a buffer from the surface texture.
2619 //
2620 // NOTE: layer transactions have taken place already, so we use their
2621 // drawing state. However, SurfaceFlinger's own transaction has not
2622 // happened yet, so we must use the current state layer list
2623 // (soon to become the drawing state list).
2624 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002625 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002626 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002627 bool first = true;
2628 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002629 // NOTE: we rely on the fact that layers are sorted by
2630 // layerStack first (so we don't have to traverse the list
2631 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002632 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002633 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002634 currentlayerStack = layerStack;
2635 // figure out if this layerstack is mirrored
2636 // (more than one display) if so, pick the default display,
2637 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002638 hintDisplay = nullptr;
2639 for (const auto& [token, display] : mDisplays) {
2640 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2641 if (hintDisplay) {
2642 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002643 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002644 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002645 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002646 }
2647 }
2648 }
2649 }
Chet Haase91d25932013-04-11 15:24:55 -07002650
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002651 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002652 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2653 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002654
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002655 // could be null when this layer is using a layerStack
2656 // that is not visible on any display. Also can occur at
2657 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002658 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002659 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002660
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002661 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002662 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002663 if (hintDisplay) {
2664 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002665 }
Robert Carr2047fae2016-11-28 14:09:09 -08002666
2667 first = false;
2668 });
Mathias Agopian84300952012-11-21 16:02:13 -08002669 }
2670
2671
Mathias Agopian3559b072012-08-15 13:46:03 -07002672 /*
2673 * Perform our own transaction if needed
2674 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002675
2676 if (mLayersAdded) {
2677 mLayersAdded = false;
2678 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002679 mVisibleRegionsDirty = true;
2680 }
2681
2682 // some layers might have been removed, so
2683 // we need to update the regions they're exposing.
2684 if (mLayersRemoved) {
2685 mLayersRemoved = false;
2686 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002687 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002688 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002689 // this layer is not visible anymore
2690 // TODO: we could traverse the tree from front to back and
2691 // compute the actual visible region
2692 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002693 Region visibleReg;
2694 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002695 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002696 }
Robert Carr2047fae2016-11-28 14:09:09 -08002697 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698 }
2699
2700 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002701
2702 updateCursorAsync();
2703}
2704
2705void SurfaceFlinger::updateCursorAsync()
2706{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002707 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002708 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002709 continue;
2710 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002711
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002712 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2713 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002714 }
2715 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002716}
2717
2718void SurfaceFlinger::commitTransaction()
2719{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002720 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002721 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002722 for (const auto& l : mLayersPendingRemoval) {
2723 recordBufferingStats(l->getName().string(),
2724 l->getOccupancyHistory(true));
Jorim Jaggi10c985e2018-10-23 11:17:45 +00002725 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002726 }
2727 mLayersPendingRemoval.clear();
2728 }
2729
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002730 // If this transaction is part of a window animation then the next frame
2731 // we composite should be considered an animation as well.
2732 mAnimCompositionPending = mAnimTransactionPending;
2733
Mathias Agopian4fec8732012-06-29 14:12:52 -07002734 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002735 // clear the "changed" flags in current state
2736 mCurrentState.colorMatrixChanged = false;
2737
Robert Carr1f0a16a2016-10-24 16:27:39 -07002738 mDrawingState.traverseInZOrder([](Layer* layer) {
2739 layer->commitChildList();
2740 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002741 mTransactionPending = false;
2742 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002743 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744}
2745
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002746void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2747 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002748 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002749 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002750
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002751 Region aboveOpaqueLayers;
2752 Region aboveCoveredLayers;
2753 Region dirty;
2754
Mathias Agopian87baae12012-07-31 12:38:26 -07002755 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756
Robert Carr2047fae2016-11-28 14:09:09 -08002757 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002759 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760
Jesse Hall01e29052013-02-19 16:13:35 -08002761 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002762 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002763 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002764 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002765
Mathias Agopianab028732010-03-16 16:41:46 -07002766 /*
2767 * opaqueRegion: area of a surface that is fully opaque.
2768 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002770
2771 /*
2772 * visibleRegion: area of a surface that is visible on screen
2773 * and not fully transparent. This is essentially the layer's
2774 * footprint minus the opaque regions above it.
2775 * Areas covered by a translucent surface are considered visible.
2776 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002778
2779 /*
2780 * coveredRegion: area of a surface that is covered by all
2781 * visible regions above it (which includes the translucent areas).
2782 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002784
Jesse Halla8026d22012-09-25 13:25:04 -07002785 /*
2786 * transparentRegion: area of a surface that is hinted to be completely
2787 * transparent. This is only used to tell when the layer has no visible
2788 * non-transparent regions and can be removed from the layer list. It
2789 * does not affect the visibleRegion of this layer or any layers
2790 * beneath it. The hint may not be correct if apps don't respect the
2791 * SurfaceView restrictions (which, sadly, some don't).
2792 */
2793 Region transparentRegion;
2794
Mathias Agopianab028732010-03-16 16:41:46 -07002795
2796 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002797 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002798 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002799 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002801 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002802 if (!visibleRegion.isEmpty()) {
2803 // Remove the transparent area from the visible region
2804 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002805 if (tr.preserveRects()) {
2806 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002807 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002808 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002809 // transformation too complex, can't do the
2810 // transparent region optimization.
2811 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002812 }
Mathias Agopianab028732010-03-16 16:41:46 -07002813 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814
Mathias Agopianab028732010-03-16 16:41:46 -07002815 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002816 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002817 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002818 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002819 // the opaque region is the layer's footprint
2820 opaqueRegion = visibleRegion;
2821 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822 }
2823 }
2824
Robert Carre5f4f692018-01-12 13:12:28 -08002825 if (visibleRegion.isEmpty()) {
2826 layer->clearVisibilityRegions();
2827 return;
2828 }
2829
Mathias Agopianab028732010-03-16 16:41:46 -07002830 // Clip the covered region to the visible region
2831 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2832
2833 // Update aboveCoveredLayers for next (lower) layer
2834 aboveCoveredLayers.orSelf(visibleRegion);
2835
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002836 // subtract the opaque region covered by the layers above us
2837 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838
2839 // compute this layer's dirty region
2840 if (layer->contentDirty) {
2841 // we need to invalidate the whole region
2842 dirty = visibleRegion;
2843 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002844 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845 layer->contentDirty = false;
2846 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002847 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002848 * the exposed region consists of two components:
2849 * 1) what's VISIBLE now and was COVERED before
2850 * 2) what's EXPOSED now less what was EXPOSED before
2851 *
2852 * note that (1) is conservative, we start with the whole
2853 * visible region but only keep what used to be covered by
2854 * something -- which mean it may have been exposed.
2855 *
2856 * (2) handles areas that were not covered by anything but got
2857 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002858 */
Mathias Agopianab028732010-03-16 16:41:46 -07002859 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002860 const Region oldVisibleRegion = layer->visibleRegion;
2861 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002862 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2863 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864 }
2865 dirty.subtractSelf(aboveOpaqueLayers);
2866
2867 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002868 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002869
Mathias Agopianab028732010-03-16 16:41:46 -07002870 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002872
Jesse Halla8026d22012-09-25 13:25:04 -07002873 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 layer->setVisibleRegion(visibleRegion);
2875 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002876 layer->setVisibleNonTransparentRegion(
2877 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002878 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879
Mathias Agopian87baae12012-07-31 12:38:26 -07002880 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881}
2882
Chia-I Wuab0c3192017-08-01 11:29:00 -07002883void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002884 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002885 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2886 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002887 }
2888 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002889}
2890
Dan Stoza6b9454d2014-11-07 16:00:59 -08002891bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002893 ALOGV("handlePageFlip");
2894
Brian Andersond6927fb2016-07-23 23:37:30 -07002895 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896
Mathias Agopian4fec8732012-06-29 14:12:52 -07002897 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002898 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002899 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002900
2901 // Store the set of layers that need updates. This set must not change as
2902 // buffers are being latched, as this could result in a deadlock.
2903 // Example: Two producers share the same command stream and:
2904 // 1.) Layer 0 is latched
2905 // 2.) Layer 0 gets a new frame
2906 // 2.) Layer 1 gets a new frame
2907 // 3.) Layer 1 is latched.
2908 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2909 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002910 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002911 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002912 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002913 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2914 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002915 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002916 } else {
2917 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002918 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002919 } else {
2920 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002921 }
Robert Carr2047fae2016-11-28 14:09:09 -08002922 });
2923
Dan Stoza9e56aa02015-11-02 13:00:03 -08002924 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002925 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002926 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002927 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002928 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002929 newDataLatched = true;
2930 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002931 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002932
Alec Mouri86770e52018-09-24 22:40:58 +00002933 // Clear the renderengine fence here...
2934 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2935 // clear instead of sp::clear.
2936 getBE().flushFence = Fence::NO_FENCE;
2937
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002938 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002939
2940 // If we will need to wake up at some time in the future to deal with a
2941 // queued frame that shouldn't be displayed during this vsync period, wake
2942 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002943 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002944 signalLayerUpdate();
2945 }
2946
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002947 // enter boot animation on first buffer latch
2948 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2949 ALOGI("Enter boot animation");
2950 mBootStage = BootStage::BOOTANIMATION;
2951 }
2952
Dan Stoza6b9454d2014-11-07 16:00:59 -08002953 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002954 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002955}
2956
Mathias Agopianad456f92011-01-13 17:53:01 -08002957void SurfaceFlinger::invalidateHwcGeometry()
2958{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002959 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002960}
2961
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002962void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2963 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002964 // We only need to actually compose the display if:
2965 // 1) It is being handled by hardware composer, which may need this to
2966 // keep its virtual display state machine in sync, or
2967 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002968 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002969 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002970 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002971 return;
2972 }
2973
Dan Stoza9e56aa02015-11-02 13:00:03 -08002974 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002975 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002976
2977 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002978 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002979}
2980
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002981bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002982 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002983
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002984 const Region bounds(display->bounds());
2985 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002986 const auto displayId = display->getId();
2987 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002988 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002989
Peiyong Lind3788632018-09-18 16:01:31 -07002990 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002991 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002992 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002993
Dan Stoza9e56aa02015-11-02 13:00:03 -08002994 if (hasClientComposition) {
2995 ALOGV("hasClientComposition");
2996
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002997 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002998 if (display->hasWideColorGamut()) {
2999 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003000 }
3001 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003002 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003003 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003004
Dominik Laskowski7e045462018-05-30 13:02:02 -07003005 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003006 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3007 HWC2::Capability::SkipClientColorTransform);
3008
Peiyong Lind3788632018-09-18 16:01:31 -07003009 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003010 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3011 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003012 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003013 }
3014
Chia-I Wud49d6692018-06-27 07:17:41 +08003015 // The current enhanced saturation matrix is designed to enhance Display P3,
3016 // thus we only apply this matrix when the render intent is not colorimetric
3017 // and the output color space is Display P3.
3018 needsEnhancedColorMatrix =
3019 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3020 outputDataspace == Dataspace::DISPLAY_P3);
3021 if (needsEnhancedColorMatrix) {
3022 colorMatrix *= mEnhancedSaturationMatrix;
3023 }
3024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003025 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003026 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003027 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003028 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003029
3030 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003031 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3032 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3033 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003034 }
3035 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003036 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003037
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003038 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003039 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003040 // when using overlays, we assume a fully transparent framebuffer
3041 // NOTE: we could reduce how much we need to clear, for instance
3042 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003043 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003044 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003045 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003046 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003047 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003048 // we're left with the letterbox region
3049 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003050 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003051
3052 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003053 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003054
Mathias Agopianb9494d52012-04-18 02:28:45 -07003055 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003056 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003057 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003058 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003059 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003060 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003061
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003062 const Rect& bounds = display->getBounds();
3063 const Rect& scissor = display->getScissor();
3064 if (scissor != bounds) {
3065 // scissor doesn't match the screen's dimensions, so we
3066 // need to clear everything outside of it and enable
3067 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003068
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003069 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003070 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003071 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003072 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003073
Mathias Agopian85d751c2012-08-29 16:59:24 -07003074 /*
3075 * and then, render the layers targeted at the framebuffer
3076 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003077
Dan Stoza9e56aa02015-11-02 13:00:03 -08003078 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003079 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003080 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003081 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003082 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003083 displayTransform.transform(layer->visibleRegion)));
3084 ALOGV("Layer: %s", layer->getName().string());
3085 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003086 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003087 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003088 case HWC2::Composition::Cursor:
3089 case HWC2::Composition::Device:
3090 case HWC2::Composition::Sideband:
3091 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003092 const Layer::State& state(layer->getDrawingState());
3093 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3094 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3095 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003096 // never clear the very first layer since we're
3097 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003098 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003099 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003100 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003101 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003102 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003103 if (layer->hasColorTransform()) {
3104 mat4 tmpMatrix;
3105 if (applyColorMatrix) {
3106 tmpMatrix = mDrawingState.colorMatrix;
3107 }
3108 tmpMatrix *= layer->getColorTransform();
3109 if (needsEnhancedColorMatrix) {
3110 tmpMatrix *= mEnhancedSaturationMatrix;
3111 }
3112 getRenderEngine().setColorTransform(tmpMatrix);
3113 } else {
3114 getRenderEngine().setColorTransform(colorMatrix);
3115 }
David Sodmanc1498e62018-09-12 14:36:26 -07003116 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003117 break;
3118 }
3119 default:
3120 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003121 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003122 } else {
3123 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003124 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003125 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003126 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003127
Peiyong Lind3788632018-09-18 16:01:31 -07003128 // Clear color transform matrix at the end of the frame.
3129 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003130
Mathias Agopianf45c5102012-10-24 16:29:17 -07003131 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003132 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003133 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134}
3135
Chia-I Wu28e3a252018-09-07 12:05:02 -07003136void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003137 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003138 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139}
3140
Dan Stoza7d89d062015-04-30 13:29:25 -07003141status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003142 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003143 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003144 const sp<Layer>& lbc,
3145 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003146{
Dan Stoza7d89d062015-04-30 13:29:25 -07003147 // add this layer to the current state list
3148 {
3149 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003150 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003151 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3152 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003153 return NO_MEMORY;
3154 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003155 if (parent == nullptr) {
3156 mCurrentState.layersSortedByZ.add(lbc);
3157 } else {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003158 if (parent->isPendingRemoval()) {
3159 ALOGE("addClientLayer called with a removed parent");
3160 return NAME_NOT_FOUND;
3161 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003162 parent->addChild(lbc);
3163 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003164
Yiwei Zhang243b3782018-05-15 17:40:04 -07003165 if (gbc != nullptr) {
3166 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3167 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3168 mMaxGraphicBufferProducerListSize,
3169 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3170 mGraphicBufferProducerList.size(),
3171 mMaxGraphicBufferProducerListSize, mNumLayers);
3172 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003173 mLayersAdded = true;
3174 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003175 }
3176
Mathias Agopian96f08192010-06-02 23:28:45 -07003177 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003178 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003179
Dan Stoza7d89d062015-04-30 13:29:25 -07003180 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003181}
3182
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003183status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003184 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003185 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3186}
Robert Carr7f9b8992017-03-10 11:08:39 -08003187
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003188status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
chaviwca27f252018-02-06 16:46:39 -08003189 bool topLevelOnly) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003190 if (layer->isPendingRemoval()) {
3191 return NO_ERROR;
3192 }
3193
Robert Carr1f0a16a2016-10-24 16:27:39 -07003194 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003195 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003196 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003197 if (topLevelOnly) {
3198 return NO_ERROR;
3199 }
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003200
3201 sp<Layer> ancestor = p;
3202 while (ancestor->getParent() != nullptr) {
3203 ancestor = ancestor->getParent();
3204 }
3205 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3206 ALOGE("removeLayer called with a layer whose parent has been removed");
3207 return NAME_NOT_FOUND;
3208 }
3209
Chia-I Wufae51c42017-06-15 12:53:59 -07003210 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003211 } else {
3212 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003213 }
3214
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003215 // As a matter of normal operation, the LayerCleaner will produce a second
3216 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3217 // so we will succeed in promoting it, but it's already been removed
3218 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3219 // otherwise something has gone wrong and we are leaking the layer.
3220 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
3221 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3222 layer->getName().string(),
3223 (p != nullptr) ? p->getName().string() : "no-parent");
3224 return BAD_VALUE;
3225 } else if (index < 0) {
3226 return NO_ERROR;
3227 }
Robert Carrf478f9f2018-10-15 12:43:33 -07003228
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003229 layer->onRemovedFromCurrentState();
3230 mLayersPendingRemoval.add(layer);
3231 mLayersRemoved = true;
3232 mNumLayers -= 1 + layer->getChildrenCount();
3233 setTransactionFlags(eTransactionNeeded);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003234 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003235}
3236
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003237uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003238 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003239}
3240
Mathias Agopian3f844832013-08-07 21:24:32 -07003241uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003242 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003243}
3244
Mathias Agopian3f844832013-08-07 21:24:32 -07003245uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003246 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003247}
3248
3249uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003250 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003251 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003252 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003253 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003254 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003255 }
3256 return old;
3257}
3258
chaviwca27f252018-02-06 16:46:39 -08003259bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3260 for (const ComposerState& state : states) {
3261 // Here we need to check that the interface we're given is indeed
3262 // one of our own. A malicious client could give us a nullptr
3263 // IInterface, or one of its own or even one of our own but a
3264 // different type. All these situations would cause us to crash.
3265 if (state.client == nullptr) {
3266 return true;
3267 }
3268
3269 sp<IBinder> binder = IInterface::asBinder(state.client);
3270 if (binder == nullptr) {
3271 return true;
3272 }
3273
3274 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3275 return true;
3276 }
3277 }
3278 return false;
3279}
3280
Mathias Agopian8b33f032012-07-24 20:43:54 -07003281void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003282 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003283 const Vector<DisplayState>& displays,
3284 uint32_t flags)
3285{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003286 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003287 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003288 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003289
chaviwca27f252018-02-06 16:46:39 -08003290 if (containsAnyInvalidClientState(states)) {
3291 return;
3292 }
3293
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003294 if (flags & eAnimation) {
3295 // For window updates that are part of an animation we must wait for
3296 // previous animation "frames" to be handled.
3297 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003298 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003299 if (CC_UNLIKELY(err != NO_ERROR)) {
3300 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003301 // caller after a few seconds.
3302 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3303 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003304 mAnimTransactionPending = false;
3305 break;
3306 }
3307 }
3308 }
3309
chaviwca27f252018-02-06 16:46:39 -08003310 for (const DisplayState& display : displays) {
3311 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003312 }
3313
chaviwca27f252018-02-06 16:46:39 -08003314 for (const ComposerState& state : states) {
3315 transactionFlags |= setClientStateLocked(state);
3316 }
3317
3318 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3319 // as destroyed should only occur after setting all other states. This is to allow for a
3320 // child re-parent to happen before marking its original parent as destroyed (which would
3321 // then mark the child as destroyed).
3322 for (const ComposerState& state : states) {
3323 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003324 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003325
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003326 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3327 // anyway. This can be used as a flush mechanism for previous async transactions.
3328 // Empty animation transaction can be used to simulate back-pressure, so also force a
3329 // transaction for empty animation transactions.
3330 if (transactionFlags == 0 &&
3331 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003332 transactionFlags = eTransactionNeeded;
3333 }
3334
Mathias Agopian386aa982011-11-07 21:58:03 -08003335 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003336 if (mInterceptor->isEnabled()) {
3337 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003338 }
Irvel468051e2016-06-13 16:44:44 -07003339
Mathias Agopian386aa982011-11-07 21:58:03 -08003340 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003341 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3342 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003343 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003344
3345 // if this is a synchronous transaction, wait for it to take effect
3346 // before returning.
3347 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003348 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003349 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003350 if (flags & eAnimation) {
3351 mAnimTransactionPending = true;
3352 }
3353 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003354 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3355 if (CC_UNLIKELY(err != NO_ERROR)) {
3356 // just in case something goes wrong in SF, return to the
3357 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003358 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3359 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003360 break;
3361 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003362 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003363 }
3364}
3365
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003366uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3367 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3368 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003369
Mathias Agopiane57f2922012-08-09 16:29:12 -07003370 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003371 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3372
3373 const uint32_t what = s.what;
3374 if (what & DisplayState::eSurfaceChanged) {
3375 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3376 state.surface = s.surface;
3377 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003378 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003379 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003380 if (what & DisplayState::eLayerStackChanged) {
3381 if (state.layerStack != s.layerStack) {
3382 state.layerStack = s.layerStack;
3383 flags |= eDisplayTransactionNeeded;
3384 }
3385 }
3386 if (what & DisplayState::eDisplayProjectionChanged) {
3387 if (state.orientation != s.orientation) {
3388 state.orientation = s.orientation;
3389 flags |= eDisplayTransactionNeeded;
3390 }
3391 if (state.frame != s.frame) {
3392 state.frame = s.frame;
3393 flags |= eDisplayTransactionNeeded;
3394 }
3395 if (state.viewport != s.viewport) {
3396 state.viewport = s.viewport;
3397 flags |= eDisplayTransactionNeeded;
3398 }
3399 }
3400 if (what & DisplayState::eDisplaySizeChanged) {
3401 if (state.width != s.width) {
3402 state.width = s.width;
3403 flags |= eDisplayTransactionNeeded;
3404 }
3405 if (state.height != s.height) {
3406 state.height = s.height;
3407 flags |= eDisplayTransactionNeeded;
3408 }
3409 }
3410
Mathias Agopiane57f2922012-08-09 16:29:12 -07003411 return flags;
3412}
3413
Robert Carrd4ae7f32018-06-07 16:10:57 -07003414bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3415 IPCThreadState* ipc = IPCThreadState::self();
3416 const int pid = ipc->getCallingPid();
3417 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003418 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003419 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003420 return false;
3421 }
3422 return true;
3423}
3424
chaviwca27f252018-02-06 16:46:39 -08003425uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3426 const layer_state_t& s = composerState.state;
3427 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3428
Mathias Agopian13127d82013-03-05 17:47:11 -08003429 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003430 if (layer == nullptr) {
3431 return 0;
3432 }
3433
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003434 if (layer->isPendingRemoval()) {
3435 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3436 return 0;
3437 }
3438
chaviw8b3871a2017-11-01 17:41:01 -07003439 uint32_t flags = 0;
3440
3441 const uint32_t what = s.what;
3442 bool geometryAppliesWithResize =
3443 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003444
3445 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3446 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003447 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003448 layer->pushPendingState();
3449 }
3450
chaviw8b3871a2017-11-01 17:41:01 -07003451 if (what & layer_state_t::ePositionChanged) {
3452 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3453 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003454 }
chaviw8b3871a2017-11-01 17:41:01 -07003455 }
3456 if (what & layer_state_t::eLayerChanged) {
3457 // NOTE: index needs to be calculated before we update the state
3458 const auto& p = layer->getParent();
3459 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003460 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003461 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003462 mCurrentState.layersSortedByZ.removeAt(idx);
3463 mCurrentState.layersSortedByZ.add(layer);
3464 // we need traversal (state changed)
3465 // AND transaction (list changed)
3466 flags |= eTransactionNeeded|eTraversalNeeded;
3467 }
chaviw8b3871a2017-11-01 17:41:01 -07003468 } else {
3469 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003470 flags |= eTransactionNeeded|eTraversalNeeded;
3471 }
3472 }
chaviw8b3871a2017-11-01 17:41:01 -07003473 }
3474 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003475 // NOTE: index needs to be calculated before we update the state
3476 const auto& p = layer->getParent();
3477 if (p == nullptr) {
3478 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3479 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3480 mCurrentState.layersSortedByZ.removeAt(idx);
3481 mCurrentState.layersSortedByZ.add(layer);
3482 // we need traversal (state changed)
3483 // AND transaction (list changed)
3484 flags |= eTransactionNeeded|eTraversalNeeded;
3485 }
3486 } else {
3487 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3488 flags |= eTransactionNeeded|eTraversalNeeded;
3489 }
chaviw8b3871a2017-11-01 17:41:01 -07003490 }
3491 }
3492 if (what & layer_state_t::eSizeChanged) {
3493 if (layer->setSize(s.w, s.h)) {
3494 flags |= eTraversalNeeded;
3495 }
3496 }
3497 if (what & layer_state_t::eAlphaChanged) {
3498 if (layer->setAlpha(s.alpha))
3499 flags |= eTraversalNeeded;
3500 }
3501 if (what & layer_state_t::eColorChanged) {
3502 if (layer->setColor(s.color))
3503 flags |= eTraversalNeeded;
3504 }
Peiyong Lind3788632018-09-18 16:01:31 -07003505 if (what & layer_state_t::eColorTransformChanged) {
3506 if (layer->setColorTransform(s.colorTransform)) {
3507 flags |= eTraversalNeeded;
3508 }
3509 }
chaviw8b3871a2017-11-01 17:41:01 -07003510 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003511 // TODO: b/109894387
3512 //
3513 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3514 // rotation. To see the problem observe that if we have a square parent, and a child
3515 // of the same size, then we rotate the child 45 degrees around it's center, the child
3516 // must now be cropped to a non rectangular 8 sided region.
3517 //
3518 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3519 // private API, and the WindowManager only uses rotation in one case, which is on a top
3520 // level layer in which cropping is not an issue.
3521 //
3522 // However given that abuse of rotation matrices could lead to surfaces extending outside
3523 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3524 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3525 // transformations.
3526 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003527 flags |= eTraversalNeeded;
3528 }
3529 if (what & layer_state_t::eTransparentRegionChanged) {
3530 if (layer->setTransparentRegionHint(s.transparentRegion))
3531 flags |= eTraversalNeeded;
3532 }
3533 if (what & layer_state_t::eFlagsChanged) {
3534 if (layer->setFlags(s.flags, s.mask))
3535 flags |= eTraversalNeeded;
3536 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003537 if (what & layer_state_t::eCropChanged_legacy) {
3538 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003539 flags |= eTraversalNeeded;
3540 }
chaviw8b3871a2017-11-01 17:41:01 -07003541 if (what & layer_state_t::eLayerStackChanged) {
3542 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3543 // We only allow setting layer stacks for top level layers,
3544 // everything else inherits layer stack from its parent.
3545 if (layer->hasParent()) {
3546 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3547 layer->getName().string());
3548 } else if (idx < 0) {
3549 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3550 "that also does not appear in the top level layer list. Something"
3551 " has gone wrong.", layer->getName().string());
3552 } else if (layer->setLayerStack(s.layerStack)) {
3553 mCurrentState.layersSortedByZ.removeAt(idx);
3554 mCurrentState.layersSortedByZ.add(layer);
3555 // we need traversal (state changed)
3556 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003557 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003558 }
3559 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003560 if (what & layer_state_t::eDeferTransaction_legacy) {
3561 if (s.barrierHandle_legacy != nullptr) {
3562 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3563 } else if (s.barrierGbp_legacy != nullptr) {
3564 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003565 if (authenticateSurfaceTextureLocked(gbp)) {
3566 const auto& otherLayer =
3567 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003568 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003569 } else {
3570 ALOGE("Attempt to defer transaction to to an"
3571 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003572 }
3573 }
chaviw8b3871a2017-11-01 17:41:01 -07003574 // We don't trigger a traversal here because if no other state is
3575 // changed, we don't want this to cause any more work
3576 }
3577 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003578 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003579 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003580 if (!hadParent) {
3581 mCurrentState.layersSortedByZ.remove(layer);
3582 }
chaviw8b3871a2017-11-01 17:41:01 -07003583 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003584 }
chaviw8b3871a2017-11-01 17:41:01 -07003585 }
3586 if (what & layer_state_t::eReparentChildren) {
3587 if (layer->reparentChildren(s.reparentHandle)) {
3588 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003589 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003590 }
chaviw8b3871a2017-11-01 17:41:01 -07003591 if (what & layer_state_t::eDetachChildren) {
3592 layer->detachChildren();
3593 }
3594 if (what & layer_state_t::eOverrideScalingModeChanged) {
3595 layer->setOverrideScalingMode(s.overrideScalingMode);
3596 // We don't trigger a traversal here because if no other state is
3597 // changed, we don't want this to cause any more work
3598 }
Marissa Wall61c58622018-07-18 10:12:20 -07003599 if (what & layer_state_t::eTransformChanged) {
3600 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3601 }
3602 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3603 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3604 flags |= eTraversalNeeded;
3605 }
3606 if (what & layer_state_t::eCropChanged) {
3607 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3608 }
3609 if (what & layer_state_t::eBufferChanged) {
3610 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3611 }
3612 if (what & layer_state_t::eAcquireFenceChanged) {
3613 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3614 }
3615 if (what & layer_state_t::eDataspaceChanged) {
3616 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3617 }
3618 if (what & layer_state_t::eHdrMetadataChanged) {
3619 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3620 }
3621 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3622 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3623 }
3624 if (what & layer_state_t::eApiChanged) {
3625 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3626 }
3627 if (what & layer_state_t::eSidebandStreamChanged) {
3628 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3629 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003630 return flags;
3631}
3632
chaviwca27f252018-02-06 16:46:39 -08003633void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3634 const layer_state_t& state = composerState.state;
3635 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3636
3637 sp<Layer> layer(client->getLayerUser(state.surface));
3638 if (layer == nullptr) {
3639 return;
3640 }
3641
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003642 if (layer->isPendingRemoval()) {
3643 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3644 return;
3645 }
3646
chaviwca27f252018-02-06 16:46:39 -08003647 if (state.what & layer_state_t::eDestroySurface) {
3648 removeLayerLocked(mStateLock, layer);
3649 }
3650}
3651
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003652status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003653 const String8& name,
3654 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003655 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003656 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003657 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003658{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003659 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003660 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003661 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003662 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003663 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003664
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003665 status_t result = NO_ERROR;
3666
3667 sp<Layer> layer;
3668
Cody Northropbc755282017-03-31 12:00:08 -06003669 String8 uniqueName = getUniqueLayerName(name);
3670
Mathias Agopian3165cc22012-08-08 19:42:09 -07003671 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003672 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003673 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3674 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003675
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003676 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003677 case ISurfaceComposerClient::eFXSurfaceBufferState:
3678 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3679 break;
chaviw13fdc492017-06-27 12:40:18 -07003680 case ISurfaceComposerClient::eFXSurfaceColor:
3681 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003682 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003683 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003684 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003685 case ISurfaceComposerClient::eFXSurfaceContainer:
3686 result = createContainerLayer(client,
3687 uniqueName, w, h, flags,
3688 handle, &layer);
3689 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003690 default:
3691 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003692 break;
3693 }
3694
Dan Stoza7d89d062015-04-30 13:29:25 -07003695 if (result != NO_ERROR) {
3696 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003697 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003698
Chia-I Wuab0c3192017-08-01 11:29:00 -07003699 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3700 // TODO b/64227542
3701 if (windowType == 441731) {
3702 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3703 layer->setPrimaryDisplayOnly();
3704 }
3705
Albert Chaulk479c60c2017-01-27 14:21:34 -05003706 layer->setInfo(windowType, ownerUid);
3707
Robert Carr1f0a16a2016-10-24 16:27:39 -07003708 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003709 if (result != NO_ERROR) {
3710 return result;
3711 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003712 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003713
3714 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003715 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003716}
3717
Cody Northropbc755282017-03-31 12:00:08 -06003718String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3719{
3720 bool matchFound = true;
3721 uint32_t dupeCounter = 0;
3722
3723 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3724 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3725
Dan Stoza436ccf32018-06-21 12:10:12 -07003726 // Grab the state lock since we're accessing mCurrentState
3727 Mutex::Autolock lock(mStateLock);
3728
Cody Northropbc755282017-03-31 12:00:08 -06003729 // Loop over layers until we're sure there is no matching name
3730 while (matchFound) {
3731 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003732 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003733 if (layer->getName() == uniqueName) {
3734 matchFound = true;
3735 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3736 }
3737 });
3738 }
3739
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003740 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3741 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003742
3743 return uniqueName;
3744}
3745
Marissa Wallfd668622018-05-10 10:21:13 -07003746status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3747 uint32_t w, uint32_t h, uint32_t flags,
3748 PixelFormat& format, sp<IBinder>* handle,
3749 sp<IGraphicBufferProducer>* gbp,
3750 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003751 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003752 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003753 case PIXEL_FORMAT_TRANSPARENT:
3754 case PIXEL_FORMAT_TRANSLUCENT:
3755 format = PIXEL_FORMAT_RGBA_8888;
3756 break;
3757 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003758 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003759 break;
3760 }
3761
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003762 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003763 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003764 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003765 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003766 *handle = layer->getHandle();
3767 *gbp = layer->getProducer();
3768 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003769 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003770
Marissa Wallfd668622018-05-10 10:21:13 -07003771 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003772 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003773}
3774
Marissa Wall61c58622018-07-18 10:12:20 -07003775status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3776 uint32_t w, uint32_t h, uint32_t flags,
3777 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003778 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003779 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003780 *handle = layer->getHandle();
3781 *outLayer = layer;
3782
3783 return NO_ERROR;
3784}
3785
chaviw13fdc492017-06-27 12:40:18 -07003786status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003787 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003788 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003789{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003790 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003791 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003792 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003793}
3794
Robert Carr6b3f6c52018-08-13 13:05:17 -07003795status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3796 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3797 sp<IBinder>* handle, sp<Layer>* outLayer)
3798{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003799 *outLayer =
3800 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003801 *handle = (*outLayer)->getHandle();
3802 return NO_ERROR;
3803}
3804
3805
Mathias Agopianac9fa422013-02-11 16:40:36 -08003806status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003807{
Robert Carr9524cb32017-02-13 11:32:32 -08003808 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003809 status_t err = NO_ERROR;
3810 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003811 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003812 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003813 err = removeLayer(l);
3814 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3815 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003816 }
3817 return err;
3818}
3819
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003820status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003821{
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003822 // called by ~LayerCleaner() when all references to the IBinder (handle)
3823 // are gone
3824 sp<Layer> l = layer.promote();
3825 if (l == nullptr) {
3826 // The layer has already been removed, carry on
3827 return NO_ERROR;
3828 }
3829 // If we have a parent, then we can continue to live as long as it does.
3830 return removeLayer(l, true);
Rob Carr4bba3702018-10-08 21:53:30 +00003831}
3832
Mathias Agopianb60314a2012-04-10 22:09:54 -07003833// ---------------------------------------------------------------------------
3834
Andy McFadden13a082e2012-08-24 10:16:42 -07003835void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003836 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3837 if (!displayToken) return;
3838
Jesse Hall01e29052013-02-19 16:13:35 -08003839 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003840 Vector<ComposerState> state;
3841 Vector<DisplayState> displays;
3842 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003843 d.what = DisplayState::eDisplayProjectionChanged |
3844 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003845 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003846 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003847 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003848 d.frame.makeInvalid();
3849 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003850 d.width = 0;
3851 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003852 displays.add(d);
3853 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003854
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003855 const auto display = getDisplayDevice(displayToken);
3856 if (!display) return;
3857
3858 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3859
3860 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003861 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003862 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003863
Brian Andersond0010582017-03-07 13:20:31 -08003864 // Use phase of 0 since phase is not known.
3865 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003866 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3867 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003868}
3869
3870void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003871 // Async since we may be called from the main thread.
3872 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003873}
3874
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003875void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3876 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003877 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003878 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003879
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003880 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003881 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003882 return;
3883 }
3884
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003885 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003886 ALOGW("Trying to set power mode for virtual display");
3887 return;
3888 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003889
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003890 display->setPowerMode(mode);
3891
Lloyd Pique4dccc412018-01-22 17:21:36 -08003892 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003893 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003894 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003895 if (idx < 0) {
3896 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3897 return;
3898 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003899 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003900 }
3901
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003902 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003903 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003904 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003905 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003906 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003907 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003908 if (mUseScheduler) {
3909 mScheduler->onScreenAcquired(mAppConnectionHandle);
3910 } else {
3911 mEventThread->onScreenAcquired();
3912 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003913 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003914 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003915
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003916 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003917 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003918 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003919
3920 struct sched_param param = {0};
3921 param.sched_priority = 1;
3922 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3923 ALOGW("Couldn't set SCHED_FIFO on display on");
3924 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003925 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003926 // Turn off the display
3927 struct sched_param param = {0};
3928 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3929 ALOGW("Couldn't set SCHED_OTHER on display off");
3930 }
3931
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003932 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003933 if (mUseScheduler) {
3934 mScheduler->disableHardwareVsync(true);
3935 } else {
3936 disableHardwareVsync(true); // also cancels any in-progress resync
3937 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003938 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003939 if (mUseScheduler) {
3940 mScheduler->onScreenReleased(mAppConnectionHandle);
3941 } else {
3942 mEventThread->onScreenReleased();
3943 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003944 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003945
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003946 getHwComposer().setPowerMode(type, mode);
3947 mVisibleRegionsDirty = true;
3948 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003949 } else if (mode == HWC_POWER_MODE_DOZE ||
3950 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003951 // Update display while dozing
3952 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003953 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003954 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003955 if (mUseScheduler) {
3956 mScheduler->onScreenAcquired(mAppConnectionHandle);
3957 } else {
3958 mEventThread->onScreenAcquired();
3959 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003960 resyncToHardwareVsync(true);
3961 }
3962 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3963 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003964 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003965 if (mUseScheduler) {
3966 mScheduler->disableHardwareVsync(true);
3967 } else {
3968 disableHardwareVsync(true); // also cancels any in-progress resync
3969 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003970 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003971 if (mUseScheduler) {
3972 mScheduler->onScreenReleased(mAppConnectionHandle);
3973 } else {
3974 mEventThread->onScreenReleased();
3975 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003976 }
3977 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003978 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003979 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003980 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003981 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003982
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003983 if (display->isPrimary()) {
3984 mTimeStats.setPowerMode(mode);
3985 }
3986
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003987 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003988}
3989
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003990void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003991 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003992 const auto display = getDisplayDevice(displayToken);
3993 if (!display) {
3994 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3995 displayToken.get());
3996 } else if (display->isVirtual()) {
3997 ALOGW("Attempt to set power mode %d for virtual display", mode);
3998 } else {
3999 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004000 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004001 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004002}
4003
4004// ---------------------------------------------------------------------------
4005
Lloyd Pique755e3192018-01-31 16:46:15 -08004006status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4007 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004008 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004009
Mathias Agopianbd115332013-04-18 16:41:04 -07004010 IPCThreadState* ipc = IPCThreadState::self();
4011 const int pid = ipc->getCallingPid();
4012 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004013
Mathias Agopianbd115332013-04-18 16:41:04 -07004014 if ((uid != AID_SHELL) &&
4015 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004016 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004017 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004018 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004019 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004020 // (this would indicate SF is stuck, but we want to be able to
4021 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004022 status_t err = mStateLock.timedLock(s2ns(1));
4023 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004024 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004025 result.appendFormat(
4026 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4027 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004028 }
4029
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004030 bool dumpAll = true;
4031 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004032 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004033
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004034 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004035 if ((index < numArgs) &&
4036 (args[index] == String16("--list"))) {
4037 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004038 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004039 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004040 }
4041
4042 if ((index < numArgs) &&
4043 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004044 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004045 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004046 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004047 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004048
4049 if ((index < numArgs) &&
4050 (args[index] == String16("--latency-clear"))) {
4051 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004052 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004053 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004054 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004055
4056 if ((index < numArgs) &&
4057 (args[index] == String16("--dispsync"))) {
4058 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004059 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004060 dumpAll = false;
4061 }
Dan Stozab90cf072015-03-05 11:05:59 -08004062
4063 if ((index < numArgs) &&
4064 (args[index] == String16("--static-screen"))) {
4065 index++;
4066 dumpStaticScreenStats(result);
4067 dumpAll = false;
4068 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004069
4070 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004071 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004072 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004073 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004074 dumpAll = false;
4075 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004076
4077 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4078 index++;
4079 dumpWideColorInfo(result);
4080 dumpAll = false;
4081 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004082
4083 if ((index < numArgs) &&
4084 (args[index] == String16("--enable-layer-stats"))) {
4085 index++;
4086 mLayerStats.enable();
4087 dumpAll = false;
4088 }
4089
4090 if ((index < numArgs) &&
4091 (args[index] == String16("--disable-layer-stats"))) {
4092 index++;
4093 mLayerStats.disable();
4094 dumpAll = false;
4095 }
4096
4097 if ((index < numArgs) &&
4098 (args[index] == String16("--clear-layer-stats"))) {
4099 index++;
4100 mLayerStats.clear();
4101 dumpAll = false;
4102 }
4103
4104 if ((index < numArgs) &&
4105 (args[index] == String16("--dump-layer-stats"))) {
4106 index++;
4107 mLayerStats.dump(result);
4108 dumpAll = false;
4109 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004110
4111 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004112 (args[index] == String16("--frame-composition"))) {
4113 index++;
4114 dumpFrameCompositionInfo(result);
4115 dumpAll = false;
4116 }
4117
4118 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004119 (args[index] == String16("--display-identification"))) {
4120 index++;
4121 dumpDisplayIdentificationData(result);
4122 dumpAll = false;
4123 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004124
4125 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4126 index++;
4127 mTimeStats.parseArgs(asProto, args, index, result);
4128 dumpAll = false;
4129 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004130 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004131
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004132 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004133 if (asProto) {
4134 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4135 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4136 } else {
4137 dumpAllLocked(args, index, result);
4138 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004139 }
4140
Mathias Agopian9795c422009-08-26 16:36:26 -07004141 if (locked) {
4142 mStateLock.unlock();
4143 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004144 }
4145 write(fd, result.string(), result.size());
4146 return NO_ERROR;
4147}
4148
Dan Stozac7014012014-02-14 15:03:43 -08004149void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4150 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004151{
Robert Carr2047fae2016-11-28 14:09:09 -08004152 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004153 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004154 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004155}
4156
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004157void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004158 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004159{
4160 String8 name;
4161 if (index < args.size()) {
4162 name = String8(args[index]);
4163 index++;
4164 }
4165
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004166 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4167 getHwComposer().isConnected(displayId)) {
4168 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4169 const nsecs_t period = activeConfig->getVsyncPeriod();
4170 result.appendFormat("%" PRId64 "\n", period);
4171 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004172
4173 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004174 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004175 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004176 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004177 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004178 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004179 }
Robert Carr2047fae2016-11-28 14:09:09 -08004180 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004181 }
4182}
4183
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004184void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004185 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004186{
4187 String8 name;
4188 if (index < args.size()) {
4189 name = String8(args[index]);
4190 index++;
4191 }
4192
Robert Carr2047fae2016-11-28 14:09:09 -08004193 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004194 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004195 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004196 }
Robert Carr2047fae2016-11-28 14:09:09 -08004197 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004198
Svetoslavd85084b2014-03-20 10:28:31 -07004199 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004200}
4201
Jamie Gennis6547ff42013-07-16 20:12:42 -07004202// This should only be called from the main thread. Otherwise it would need
4203// the lock and should use mCurrentState rather than mDrawingState.
4204void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004205 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004206 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004207 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004208
4209 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4210}
4211
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004212void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004213{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004214 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004215
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004216 if (isLayerTripleBufferingDisabled())
4217 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004218
4219 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004220 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004221 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004222 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004223 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4224 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004225 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004226}
4227
Dan Stozab90cf072015-03-05 11:05:59 -08004228void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4229{
4230 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004231 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4232 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004233 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004234 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004235 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4236 b + 1, bucketTimeSec, percent);
4237 }
David Sodman4a36e932017-11-07 14:29:47 -08004238 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004239 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004240 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004241 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004242 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004243}
4244
Dan Stozae77c7662016-05-13 11:37:28 -07004245void SurfaceFlinger::recordBufferingStats(const char* layerName,
4246 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004247 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4248 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004249 for (const auto& segment : history) {
4250 if (!segment.usedThirdBuffer) {
4251 stats.twoBufferTime += segment.totalTime;
4252 }
4253 if (segment.occupancyAverage < 1.0f) {
4254 stats.doubleBufferedTime += segment.totalTime;
4255 } else if (segment.occupancyAverage < 2.0f) {
4256 stats.tripleBufferedTime += segment.totalTime;
4257 }
4258 ++stats.numSegments;
4259 stats.totalTime += segment.totalTime;
4260 }
4261}
4262
Brian Andersond6927fb2016-07-23 23:37:30 -07004263void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4264 result.appendFormat("Layer frame timestamps:\n");
4265
4266 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4267 const size_t count = currentLayers.size();
4268 for (size_t i=0 ; i<count ; i++) {
4269 currentLayers[i]->dumpFrameEvents(result);
4270 }
4271}
4272
Dan Stozae77c7662016-05-13 11:37:28 -07004273void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4274 result.append("Buffering stats:\n");
4275 result.append(" [Layer name] <Active time> <Two buffer> "
4276 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004277 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004278 typedef std::tuple<std::string, float, float, float> BufferTuple;
4279 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004280 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004281 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004282 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004283 if (stats.numSegments == 0) {
4284 continue;
4285 }
4286 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4287 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4288 stats.totalTime;
4289 float doubleBufferRatio = static_cast<float>(
4290 stats.doubleBufferedTime) / stats.totalTime;
4291 float tripleBufferRatio = static_cast<float>(
4292 stats.tripleBufferedTime) / stats.totalTime;
4293 sorted.insert({activeTime, {name, twoBufferRatio,
4294 doubleBufferRatio, tripleBufferRatio}});
4295 }
4296 for (const auto& sortedPair : sorted) {
4297 float activeTime = sortedPair.first;
4298 const BufferTuple& values = sortedPair.second;
4299 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4300 std::get<0>(values).c_str(), activeTime,
4301 std::get<1>(values), std::get<2>(values),
4302 std::get<3>(values));
4303 }
4304 result.append("\n");
4305}
4306
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004307void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004308 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004309 const int32_t displayId = display->getId();
4310 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4311 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004312 continue;
4313 }
4314
Dominik Laskowski7e045462018-05-30 13:02:02 -07004315 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004316 uint8_t port;
4317 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004318 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004319 result.append("no identification data\n");
4320 continue;
4321 }
4322
4323 if (!isEdid(data)) {
4324 result.append("unknown identification data: ");
4325 for (uint8_t byte : data) {
4326 result.appendFormat("%x ", byte);
4327 }
4328 result.append("\n");
4329 continue;
4330 }
4331
4332 const auto edid = parseEdid(data);
4333 if (!edid) {
4334 result.append("invalid EDID: ");
4335 for (uint8_t byte : data) {
4336 result.appendFormat("%x ", byte);
4337 }
4338 result.append("\n");
4339 continue;
4340 }
4341
4342 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4343 result.append(edid->displayName.data(), edid->displayName.length());
4344 result.append("\"\n");
4345 }
4346 result.append("\n");
4347}
4348
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004349void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004350 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4351 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004352 result.appendFormat("DisplayColorSetting: %s\n",
4353 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004354
4355 // TODO: print out if wide-color mode is active or not
4356
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004357 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004358 const int32_t displayId = display->getId();
4359 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004360 continue;
4361 }
4362
Dominik Laskowski7e045462018-05-30 13:02:02 -07004363 result.appendFormat("Display %d color modes:\n", displayId);
4364 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004365 for (auto&& mode : modes) {
4366 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4367 }
4368
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004369 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004370 result.appendFormat(" Current color mode: %s (%d)\n",
4371 decodeColorMode(currentMode).c_str(), currentMode);
4372 }
4373 result.append("\n");
4374}
4375
David Sodman7e4ae112018-02-09 15:02:28 -08004376void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4377 std::string stringResult;
4378
4379 for (const auto& [token, display] : mDisplays) {
4380 const auto displayId = display->getId();
4381 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4382 continue;
4383 }
4384
4385 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4386 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4387 break;
4388 }
4389 const auto& compositionInfoList = compositionInfoIt->second;
4390 stringResult += base::StringPrintf("Display: %d\n", displayId);
4391 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4392 for (const auto& compositionInfo : compositionInfoList) {
4393 compositionInfo.dump(stringResult, nullptr);
4394 stringResult += base::StringPrintf("\n");
4395 }
4396 }
4397
4398 result.append(stringResult.c_str());
4399}
4400
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004401LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004402 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004403 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4404 const State& state = useDrawing ? mDrawingState : mCurrentState;
4405 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004406 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004407 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004408 });
4409
4410 return layersProto;
4411}
4412
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004413LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004414 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004415
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004416 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004417 resolution->set_w(display.getWidth());
4418 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004419
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004420 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4421 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4422 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004423
Dominik Laskowski7e045462018-05-30 13:02:02 -07004424 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004425 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004426 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004427 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004428 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004429 }
4430 });
4431
4432 return layersProto;
4433}
4434
Mathias Agopian74d211a2013-04-22 16:55:35 +02004435void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4436 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004437{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004438 bool colorize = false;
4439 if (index < args.size()
4440 && (args[index] == String16("--color"))) {
4441 colorize = true;
4442 index++;
4443 }
4444
4445 Colorizer colorizer(colorize);
4446
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004447 // figure out if we're stuck somewhere
4448 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004449 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004450 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4451
4452 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004453 * Dump library configuration.
4454 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004455
4456 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004457 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004458 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004459 appendSfConfigString(result);
4460 appendUiConfigString(result);
4461 appendGuiConfigString(result);
4462 result.append("\n");
4463
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004464 result.append("\nDisplay identification data:\n");
4465 dumpDisplayIdentificationData(result);
4466
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004467 result.append("\nWide-Color information:\n");
4468 dumpWideColorInfo(result);
4469
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004470 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004471 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004472 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004473 result.append(SyncFeatures::getInstance().toString());
4474 result.append("\n");
4475
Andy McFadden41d67d72014-04-25 16:58:34 -07004476 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004477 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004478 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004479
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004480 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4481 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004482 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4483 getHwComposer().isConnected(displayId)) {
4484 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004485 result.appendFormat("Display %d: "
4486 "app phase %" PRId64 " ns, "
4487 "sf phase %" PRId64 " ns, "
4488 "early app phase %" PRId64 " ns, "
4489 "early sf phase %" PRId64 " ns, "
4490 "early app gl phase %" PRId64 " ns, "
4491 "early sf gl phase %" PRId64 " ns, "
4492 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4493 displayId,
4494 vsyncPhaseOffsetNs,
4495 sfVsyncPhaseOffsetNs,
4496 appEarlyOffset,
4497 sfEarlyOffset,
4498 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004499 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004500 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004501 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004502 result.append("\n");
4503
Dan Stozab90cf072015-03-05 11:05:59 -08004504 // Dump static screen stats
4505 result.append("\n");
4506 dumpStaticScreenStats(result);
4507 result.append("\n");
4508
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004509 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4510
Dan Stozae77c7662016-05-13 11:37:28 -07004511 dumpBufferingStats(result);
4512
Andy McFadden4803b742012-09-24 19:07:20 -07004513 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004514 * Dump the visible layer list
4515 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004516 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004517 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004518 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4519 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004520 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004521
Chia-I Wu2f884132018-09-13 15:17:58 -07004522 {
4523 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4524 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4525 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4526 result.append("\n");
4527 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004528
David Sodman7e4ae112018-02-09 15:02:28 -08004529 result.append("\nFrame-Composition information:\n");
4530 dumpFrameCompositionInfo(result);
4531 result.append("\n");
4532
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004533 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004534 * Dump Display state
4535 */
4536
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004537 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004538 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004539 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004540 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004541 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004542 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004543 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004544
4545 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004546 * Dump SurfaceFlinger global state
4547 */
4548
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004549 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004550 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004551 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004552
Mathias Agopian888c8222012-08-04 21:10:38 -07004553 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004554 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004555
David Sodmanbc815282017-11-05 18:57:52 -08004556 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004557
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004558 if (display) {
4559 display->undefinedRegion.dump(result, "undefinedRegion");
4560 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4561 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004562 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004563 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004564 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004565 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004566
4567 if (display) {
4568 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4569 result.appendFormat(" refresh-rate : %f fps\n"
4570 " x-dpi : %f\n"
4571 " y-dpi : %f\n",
4572 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4573 activeConfig->getDpiY());
4574 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004575
Mathias Agopian74d211a2013-04-22 16:55:35 +02004576 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004577 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004578
Ana Krulec98b5b242018-08-10 15:03:23 -07004579 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004580 /*
4581 * VSYNC state
4582 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004583 if (mUseScheduler) {
4584 mScheduler->dump(mAppConnectionHandle, result);
4585 } else {
4586 mEventThread->dump(result);
4587 }
Dan Stozae22aec72016-08-01 13:20:59 -07004588 result.append("\n");
4589
4590 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004591 * Tracing state
4592 */
4593 mTracing.dump(result);
4594 result.append("\n");
4595
4596 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004597 * HWC layer minidump
4598 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004599 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004600 const int32_t displayId = display->getId();
4601 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004602 continue;
4603 }
4604
Dominik Laskowski7e045462018-05-30 13:02:02 -07004605 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004606 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004607 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004608 result.append("\n");
4609 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004610
4611 /*
4612 * Dump HWComposer state
4613 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004614 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004615 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004616 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004617 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004618 result.appendFormat(" h/w composer %s\n",
4619 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004620 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004621
4622 /*
4623 * Dump gralloc state
4624 */
4625 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4626 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004627
4628 /*
4629 * Dump VrFlinger state if in use.
4630 */
4631 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4632 result.append("VrFlinger state:\n");
4633 result.append(mVrFlinger->Dump().c_str());
4634 result.append("\n");
4635 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004636}
4637
Dominik Laskowski7e045462018-05-30 13:02:02 -07004638const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004639 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004640 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004641 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004642 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004643 }
4644 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004645
4646 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4647 static const Vector<sp<Layer>> empty;
4648 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004649}
4650
Keun young Park63f165f2012-08-31 10:53:36 -07004651bool SurfaceFlinger::startDdmConnection()
4652{
4653 void* libddmconnection_dso =
4654 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4655 if (!libddmconnection_dso) {
4656 return false;
4657 }
4658 void (*DdmConnection_start)(const char* name);
4659 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004660 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004661 if (!DdmConnection_start) {
4662 dlclose(libddmconnection_dso);
4663 return false;
4664 }
4665 (*DdmConnection_start)(getServiceName());
4666 return true;
4667}
4668
Chia-I Wu28f320b2018-05-03 11:02:56 -07004669void SurfaceFlinger::updateColorMatrixLocked() {
4670 mat4 colorMatrix;
4671 if (mGlobalSaturationFactor != 1.0f) {
4672 // Rec.709 luma coefficients
4673 float3 luminance{0.213f, 0.715f, 0.072f};
4674 luminance *= 1.0f - mGlobalSaturationFactor;
4675 mat4 saturationMatrix = mat4(
4676 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4677 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4678 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4679 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4680 );
4681 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4682 } else {
4683 colorMatrix = mClientColorMatrix * mDaltonizer();
4684 }
4685
4686 if (mCurrentState.colorMatrix != colorMatrix) {
4687 mCurrentState.colorMatrix = colorMatrix;
4688 mCurrentState.colorMatrixChanged = true;
4689 setTransactionFlags(eTransactionNeeded);
4690 }
4691}
4692
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004693status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004694#pragma clang diagnostic push
4695#pragma clang diagnostic error "-Wswitch-enum"
4696 switch (static_cast<ISurfaceComposerTag>(code)) {
4697 // These methods should at minimum make sure that the client requested
4698 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004699 case BOOT_FINISHED:
4700 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004701 case CREATE_CONNECTION:
4702 case CREATE_DISPLAY:
4703 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004704 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004705 case GET_ACTIVE_COLOR_MODE:
4706 case GET_ANIMATION_FRAME_STATS:
4707 case GET_HDR_CAPABILITIES:
4708 case SET_ACTIVE_CONFIG:
4709 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004710 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004711 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004712 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4713 IPCThreadState* ipc = IPCThreadState::self();
4714 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4715 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004716 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004717 }
Robert Carr1db73f62016-12-21 12:58:51 -08004718 return OK;
4719 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004720 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004721 IPCThreadState* ipc = IPCThreadState::self();
4722 const int pid = ipc->getCallingPid();
4723 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004724 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4725 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004726 return PERMISSION_DENIED;
4727 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004728 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004729 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004730 // Used by apps to hook Choreographer to SurfaceFlinger.
4731 case CREATE_DISPLAY_EVENT_CONNECTION:
4732 // The following calls are currently used by clients that do not
4733 // request necessary permissions. However, they do not expose any secret
4734 // information, so it is OK to pass them.
4735 case AUTHENTICATE_SURFACE:
4736 case GET_ACTIVE_CONFIG:
4737 case GET_BUILT_IN_DISPLAY:
4738 case GET_DISPLAY_COLOR_MODES:
4739 case GET_DISPLAY_CONFIGS:
4740 case GET_DISPLAY_STATS:
4741 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4742 // Calling setTransactionState is safe, because you need to have been
4743 // granted a reference to Client* and Handle* to do anything with it.
4744 case SET_TRANSACTION_STATE:
4745 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004746 case CREATE_SCOPED_CONNECTION:
4747 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004748 return OK;
4749 }
4750 case CAPTURE_LAYERS:
4751 case CAPTURE_SCREEN: {
4752 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004753 IPCThreadState* ipc = IPCThreadState::self();
4754 const int pid = ipc->getCallingPid();
4755 const int uid = ipc->getCallingUid();
4756 if ((uid != AID_GRAPHICS) &&
4757 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4758 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4759 return PERMISSION_DENIED;
4760 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004761 return OK;
4762 }
4763 // The following codes are deprecated and should never be allowed to access SF.
4764 case CONNECT_DISPLAY_UNUSED:
4765 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4766 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4767 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004768 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004769 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004770
4771 // These codes are used for the IBinder protocol to either interrogate the recipient
4772 // side of the transaction for its canonical interface descriptor or to dump its state.
4773 // We let them pass by default.
4774 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4775 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4776 code == IBinder::SYSPROPS_TRANSACTION) {
4777 return OK;
4778 }
Peiyong Lin3b44a032018-10-24 18:18:12 -07004779 // Numbers from 1000 to 1030 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004780 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin3b44a032018-10-24 18:18:12 -07004781 if (code >= 1000 && code <= 1030) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004782 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4783 return OK;
4784 }
4785 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4786 return PERMISSION_DENIED;
4787#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004788}
4789
Ana Krulec13be8ad2018-08-21 02:43:56 +00004790status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4791 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004792 status_t credentialCheck = CheckTransactCodeCredentials(code);
4793 if (credentialCheck != OK) {
4794 return credentialCheck;
4795 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004796
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004797 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4798 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004799 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004800 IPCThreadState* ipc = IPCThreadState::self();
4801 const int uid = ipc->getCallingUid();
4802 if (CC_UNLIKELY(uid != AID_SYSTEM
4803 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004804 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004805 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004806 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004807 return PERMISSION_DENIED;
4808 }
4809 int n;
4810 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004811 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004812 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004813 return NO_ERROR;
4814 case 1002: // SHOW_UPDATES
4815 n = data.readInt32();
4816 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004817 invalidateHwcGeometry();
4818 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004819 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004820 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004821 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004822 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004823 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004824 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004825 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004826 setTransactionFlags(
4827 eTransactionNeeded|
4828 eDisplayTransactionNeeded|
4829 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004830 return NO_ERROR;
4831 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004832 case 1006:{ // send empty update
4833 signalRefresh();
4834 return NO_ERROR;
4835 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004836 case 1008: // toggle use of hw composer
4837 n = data.readInt32();
4838 mDebugDisableHWC = n ? 1 : 0;
4839 invalidateHwcGeometry();
4840 repaintEverything();
4841 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004842 case 1009: // toggle use of transform hint
4843 n = data.readInt32();
4844 mDebugDisableTransformHint = n ? 1 : 0;
4845 invalidateHwcGeometry();
4846 repaintEverything();
4847 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004848 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004849 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004850 reply->writeInt32(0);
4851 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004852 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004853 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004854 return NO_ERROR;
4855 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004856 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004857 if (!display) {
4858 return NAME_NOT_FOUND;
4859 }
4860
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004861 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004862 return NO_ERROR;
4863 }
4864 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004865 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004866 // daltonize
4867 n = data.readInt32();
4868 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004869 case 1:
4870 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4871 break;
4872 case 2:
4873 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4874 break;
4875 case 3:
4876 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4877 break;
4878 default:
4879 mDaltonizer.setType(ColorBlindnessType::None);
4880 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004881 }
4882 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004883 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004884 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004885 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004886 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004887
4888 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004889 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004890 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004891 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004892 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004893 // apply a color matrix
4894 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004895 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004896 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004897 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004898 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004899 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004900 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004901 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004902 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004903 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004904 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004905
4906 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4907 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004908 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004909 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4910 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4911 }
4912
Chia-I Wu28f320b2018-05-03 11:02:56 -07004913 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004914 return NO_ERROR;
4915 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004916 // This is an experimental interface
4917 // Needs to be shifted to proper binder interface when we productize
4918 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004919 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004920 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004921 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004922 return NO_ERROR;
4923 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004924 case 1017: {
4925 n = data.readInt32();
4926 mForceFullDamage = static_cast<bool>(n);
4927 return NO_ERROR;
4928 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004929 case 1018: { // Modify Choreographer's phase offset
4930 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004931 if (mUseScheduler) {
4932 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4933 } else {
4934 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4935 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004936 return NO_ERROR;
4937 }
4938 case 1019: { // Modify SurfaceFlinger's phase offset
4939 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004940 if (mUseScheduler) {
4941 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4942 } else {
4943 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4944 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004945 return NO_ERROR;
4946 }
Irvel468051e2016-06-13 16:44:44 -07004947 case 1020: { // Layer updates interceptor
4948 n = data.readInt32();
4949 if (n) {
4950 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004951 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004952 }
4953 else{
4954 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004955 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004956 }
4957 return NO_ERROR;
4958 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004959 case 1021: { // Disable HWC virtual displays
4960 n = data.readInt32();
4961 mUseHwcVirtualDisplays = !n;
4962 return NO_ERROR;
4963 }
Romain Guy0147a172017-06-01 13:53:56 -07004964 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004965 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004966 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004967
Chia-I Wu28f320b2018-05-03 11:02:56 -07004968 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004969 return NO_ERROR;
4970 }
Romain Guy54f154a2017-10-24 21:40:32 +01004971 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004972 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004973 invalidateHwcGeometry();
4974 repaintEverything();
4975 return NO_ERROR;
4976 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004977 // Deprecate, use 1030 to check whether the device is color managed.
4978 case 1024: {
4979 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004980 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004981 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004982 n = data.readInt32();
4983 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004984 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004985 mTracing.enable();
4986 doTracing("tracing.enable");
4987 reply->writeInt32(NO_ERROR);
4988 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004989 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004990 status_t err = mTracing.disable();
4991 reply->writeInt32(err);
4992 }
4993 return NO_ERROR;
4994 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004995 case 1026: { // Get layer tracing status
4996 reply->writeBool(mTracing.isEnabled());
4997 return NO_ERROR;
4998 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004999 // Is a DisplayColorSetting supported?
5000 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005001 const auto display = getDefaultDisplayDevice();
5002 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005003 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005004 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005005
5006 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5007 switch (setting) {
5008 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005009 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005010 break;
5011 case DisplayColorSetting::UNMANAGED:
5012 reply->writeBool(true);
5013 break;
5014 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005015 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005016 break;
5017 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005018 reply->writeBool(
5019 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005020 break;
5021 }
5022 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005023 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005024 // Is VrFlinger active?
5025 case 1028: {
5026 Mutex::Autolock _l(mStateLock);
5027 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5028 return NO_ERROR;
5029 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005030 // Is device color managed?
5031 case 1030: {
5032 reply->writeBool(useColorManagement);
5033 return NO_ERROR;
5034 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005035 }
5036 }
5037 return err;
5038}
5039
Steven Thomas6d8110b2017-08-31 18:24:21 -07005040void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005041 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005042 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005043}
5044
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005045// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5046class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005047public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005048 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5049 ~WindowDisconnector() {
5050 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005051 }
5052
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005053private:
5054 ANativeWindow* mWindow;
5055 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005056};
5057
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005058status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005059 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5060 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005061 uint32_t reqWidth, uint32_t reqHeight,
5062 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005063 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005064 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005065
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005066 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005067
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005068 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5069
Chia-I Wu20261cb2018-08-23 12:55:44 -07005070 sp<DisplayDevice> display;
5071 {
5072 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005073
Chia-I Wu20261cb2018-08-23 12:55:44 -07005074 display = getDisplayDeviceLocked(displayToken);
5075 if (!display) return BAD_VALUE;
5076
Chia-I Wu8730ba82018-08-29 09:25:59 -07005077 // ignore sourceCrop (i.e., use the projected logical display
5078 // viewport) until the framework is fixed
5079 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005080
5081 // set the requested width/height to the logical display viewport size
5082 // by default
5083 if (reqWidth == 0 || reqHeight == 0) {
5084 reqWidth = uint32_t(display->getViewport().width());
5085 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005086 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005087 }
5088
Peiyong Lin0e003c92018-09-17 11:09:51 -07005089 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5090 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005091
5092 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005093 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005094 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5095 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005096}
5097
5098status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005099 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5100 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005101 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005102 ATRACE_CALL();
5103
5104 class LayerRenderArea : public RenderArea {
5105 public:
Robert Carr578038f2018-03-09 12:25:24 -08005106 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005107 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5108 bool childrenOnly)
5109 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005110 mLayer(layer),
5111 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005112 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005113 mFlinger(flinger),
5114 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005115 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005116 Rect getBounds() const override {
5117 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005118 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005119 }
Marissa Wall61c58622018-07-18 10:12:20 -07005120 int getHeight() const override {
5121 return mLayer->getActiveHeight(mLayer->getDrawingState());
5122 }
5123 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005124 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005125 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005126 Rect getSourceCrop() const override {
5127 if (mCrop.isEmpty()) {
5128 return getBounds();
5129 } else {
5130 return mCrop;
5131 }
5132 }
Robert Carr578038f2018-03-09 12:25:24 -08005133 class ReparentForDrawing {
5134 public:
5135 const sp<Layer>& oldParent;
5136 const sp<Layer>& newParent;
5137
5138 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5139 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005140 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005141 }
Robert Carr15eae092018-03-23 13:43:53 -07005142 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005143 };
5144
5145 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005146 const Rect sourceCrop = getSourceCrop();
5147 // no need to check rotation because there is none
5148 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5149 sourceCrop.height() != getReqHeight();
5150
Robert Carr578038f2018-03-09 12:25:24 -08005151 if (!mChildrenOnly) {
5152 mTransform = mLayer->getTransform().inverse();
5153 drawLayers();
5154 } else {
5155 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005156 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005157 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5158 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005159
5160 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5161 drawLayers();
5162 }
5163 }
chaviwa76b2712017-09-20 12:02:26 -07005164
chaviwa76b2712017-09-20 12:02:26 -07005165 private:
chaviw7206d492017-11-10 16:16:12 -08005166 const sp<Layer> mLayer;
5167 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005168
5169 // In the "childrenOnly" case we reparent the children to a screenshot
5170 // layer which has no properties set and which does not draw.
5171 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005172 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005173 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005174
5175 SurfaceFlinger* mFlinger;
5176 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005177 };
5178
5179 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5180 auto parent = layerHandle->owner.promote();
5181
Jorim Jaggi10c985e2018-10-23 11:17:45 +00005182 if (parent == nullptr || parent->isPendingRemoval()) {
chaviw7206d492017-11-10 16:16:12 -08005183 ALOGE("captureLayers called with a removed parent");
5184 return NAME_NOT_FOUND;
5185 }
5186
Robert Carr578038f2018-03-09 12:25:24 -08005187 const int uid = IPCThreadState::self()->getCallingUid();
5188 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5189 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5190 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5191 return PERMISSION_DENIED;
5192 }
5193
chaviw7206d492017-11-10 16:16:12 -08005194 Rect crop(sourceCrop);
5195 if (sourceCrop.width() <= 0) {
5196 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005197 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005198 }
5199
5200 if (sourceCrop.height() <= 0) {
5201 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005202 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005203 }
5204
5205 int32_t reqWidth = crop.width() * frameScale;
5206 int32_t reqHeight = crop.height() * frameScale;
5207
Chia-I Wu20261cb2018-08-23 12:55:44 -07005208 // really small crop or frameScale
5209 if (reqWidth <= 0) {
5210 reqWidth = 1;
5211 }
5212 if (reqHeight <= 0) {
5213 reqHeight = 1;
5214 }
5215
Peiyong Lin0e003c92018-09-17 11:09:51 -07005216 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005217
Robert Carr578038f2018-03-09 12:25:24 -08005218 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005219 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5220 if (!layer->isVisible()) {
5221 return;
Robert Carr578038f2018-03-09 12:25:24 -08005222 } else if (childrenOnly && layer == parent.get()) {
5223 return;
chaviwa76b2712017-09-20 12:02:26 -07005224 }
5225 visitor(layer);
5226 });
5227 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005228 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005229}
5230
5231status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5232 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005233 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005234 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005235 bool useIdentityTransform) {
5236 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005237
Peiyong Lin0e003c92018-09-17 11:09:51 -07005238 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005239 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5240 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005241 *outBuffer =
5242 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5243 static_cast<android_pixel_format>(reqPixelFormat), 1,
5244 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005245
5246 // This mutex protects syncFd and captureResult for communication of the return values from the
5247 // main thread back to this Binder thread
5248 std::mutex captureMutex;
5249 std::condition_variable captureCondition;
5250 std::unique_lock<std::mutex> captureLock(captureMutex);
5251 int syncFd = -1;
5252 std::optional<status_t> captureResult;
5253
Robert Carr03480e22018-01-04 16:02:06 -08005254 const int uid = IPCThreadState::self()->getCallingUid();
5255 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5256
Dominik Laskowski8c001672018-05-30 16:52:06 -07005257 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005258 // If there is a refresh pending, bug out early and tell the binder thread to try again
5259 // after the refresh.
5260 if (mRefreshPending) {
5261 ATRACE_NAME("Skipping screenshot for now");
5262 std::unique_lock<std::mutex> captureLock(captureMutex);
5263 captureResult = std::make_optional<status_t>(EAGAIN);
5264 captureCondition.notify_one();
5265 return;
5266 }
5267
5268 status_t result = NO_ERROR;
5269 int fd = -1;
5270 {
5271 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005272 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005273 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5274 useIdentityTransform, forSystem, &fd);
5275 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005276 }
5277
5278 {
5279 std::unique_lock<std::mutex> captureLock(captureMutex);
5280 syncFd = fd;
5281 captureResult = std::make_optional<status_t>(result);
5282 captureCondition.notify_one();
5283 }
5284 });
5285
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005286 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005287 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005288 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005289 while (*captureResult == EAGAIN) {
5290 captureResult.reset();
5291 result = postMessageAsync(message);
5292 if (result != NO_ERROR) {
5293 return result;
5294 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005295 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005296 }
5297 result = *captureResult;
5298 }
5299
5300 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005301 sync_wait(syncFd, -1);
5302 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005303 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005304
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005305 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005306}
5307
chaviwa76b2712017-09-20 12:02:26 -07005308void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005309 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005310 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005311 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005312
Lloyd Pique144e1162017-12-20 16:44:52 -08005313 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005314
chaviwa76b2712017-09-20 12:02:26 -07005315 const auto reqWidth = renderArea.getReqWidth();
5316 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005317 const auto sourceCrop = renderArea.getSourceCrop();
5318 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005319
Peiyong Lin0e003c92018-09-17 11:09:51 -07005320 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005321 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005322
Mathias Agopian180f10d2013-04-10 22:55:41 -07005323 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005324 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005325
5326 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005327 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005328 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005329
chaviw50da5042018-04-09 13:49:37 -07005330 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005331 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005332 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005333
chaviwa76b2712017-09-20 12:02:26 -07005334 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005335 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005336 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005337 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005338 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005339}
5340
chaviwa76b2712017-09-20 12:02:26 -07005341status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5342 TraverseLayersFunction traverseLayers,
5343 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005344 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005345 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005346 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005347 ATRACE_CALL();
5348
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005349 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005350
5351 traverseLayers([&](Layer* layer) {
5352 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5353 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005354
Robert Carr03480e22018-01-04 16:02:06 -08005355 // We allow the system server to take screenshots of secure layers for
5356 // use in situations like the Screen-rotation animation and place
5357 // the impetus on WindowManager to not persist them.
5358 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005359 ALOGW("FB is protected: PERMISSION_DENIED");
5360 return PERMISSION_DENIED;
5361 }
5362
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005363 // this binds the given EGLImage as a framebuffer for the
5364 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005365 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005366 if (bufferBond.getStatus() != NO_ERROR) {
5367 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005368 return INVALID_OPERATION;
5369 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005370
Dan Stozaabcda352017-06-01 14:37:39 -07005371 // this will in fact render into our dequeued buffer
5372 // via an FBO, which means we didn't have to create
5373 // an EGLSurface and therefore we're not
5374 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005375 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005376
Alec Mouri492bc572018-09-11 21:40:04 +00005377 base::unique_fd syncFd = getRenderEngine().flush();
5378 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005379 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005380 }
Alec Mouri492bc572018-09-11 21:40:04 +00005381 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005382
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005383 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005384}
5385
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005386// ---------------------------------------------------------------------------
5387
Dan Stoza412903f2017-04-27 13:42:17 -07005388void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5389 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005390}
5391
Dan Stoza412903f2017-04-27 13:42:17 -07005392void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5393 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005394}
5395
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005396void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005397 const LayerVector::Visitor& visitor) {
5398 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005399 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005400 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005401 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005402 continue;
5403 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005404 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005405 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005406 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005407 return;
5408 }
chaviwa76b2712017-09-20 12:02:26 -07005409 if (!layer->isVisible()) {
5410 return;
5411 }
5412 visitor(layer);
5413 });
5414 }
5415}
5416
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005417}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005418
Lloyd Pique074e8122018-07-26 12:57:23 -07005419
Mathias Agopian3f844832013-08-07 21:24:32 -07005420#if defined(__gl_h_)
5421#error "don't include gl/gl.h in this file"
5422#endif
5423
5424#if defined(__gl2_h_)
5425#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005426#endif