blob: 53927fd787df8fed85c96ee5c54a1d26a206446e [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"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070086#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070087#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/EventControlThread.h"
89#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070090#include "Scheduler/InjectVSyncSource.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070091#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070092
Mathias Agopianff2ed702013-09-01 21:36:12 -070093#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070094
David Sodman7e4ae112018-02-09 15:02:28 -080095#include "android-base/stringprintf.h"
96
Jiyong Park4b20c2e2017-01-14 19:45:11 +090097#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080098#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070099#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800100#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900101#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900102
chaviw1d044282017-09-27 12:19:28 -0700103#include <layerproto/LayerProtoParser.h>
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105#define DISPLAY_COUNT 1
106
107namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108
Jaesoo Lee43518572017-01-23 19:03:16 +0900109using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700111using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700112using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700113using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700114using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
Steven Thomasb02664d2017-07-26 18:48:28 -0700116namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700117
118#pragma clang diagnostic push
119#pragma clang diagnostic error "-Wswitch-enum"
120
121bool isWideColorMode(const ColorMode colorMode) {
122 switch (colorMode) {
123 case ColorMode::DISPLAY_P3:
124 case ColorMode::ADOBE_RGB:
125 case ColorMode::DCI_P3:
126 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700127 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700128 case ColorMode::BT2100_PQ:
129 case ColorMode::BT2100_HLG:
130 return true;
131 case ColorMode::NATIVE:
132 case ColorMode::STANDARD_BT601_625:
133 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
134 case ColorMode::STANDARD_BT601_525:
135 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
136 case ColorMode::STANDARD_BT709:
137 case ColorMode::SRGB:
138 return false;
139 }
140 return false;
141}
142
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700143ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
144 switch (rotation) {
145 case ISurfaceComposer::eRotateNone:
146 return ui::Transform::ROT_0;
147 case ISurfaceComposer::eRotate90:
148 return ui::Transform::ROT_90;
149 case ISurfaceComposer::eRotate180:
150 return ui::Transform::ROT_180;
151 case ISurfaceComposer::eRotate270:
152 return ui::Transform::ROT_270;
153 }
154 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
155 return ui::Transform::ROT_0;
156}
157
Peiyong Linfca547f2018-07-09 13:03:33 -0700158#pragma clang diagnostic pop
159
Steven Thomasb02664d2017-07-26 18:48:28 -0700160class ConditionalLock {
161public:
162 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
163 if (lock) {
164 mMutex.lock();
165 }
166 }
167 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
168private:
169 Mutex& mMutex;
170 bool mLocked;
171};
Peiyong Linfca547f2018-07-09 13:03:33 -0700172
Steven Thomasb02664d2017-07-26 18:48:28 -0700173} // namespace anonymous
174
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175// ---------------------------------------------------------------------------
176
Mathias Agopian99b49842011-06-27 16:05:52 -0700177const String16 sHardwareTest("android.permission.HARDWARE_TEST");
178const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
179const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
180const String16 sDump("android.permission.DUMP");
181
182// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800183int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
184int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700185int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700186bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800187uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800188bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800189bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800190int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800191// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600192bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700193int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700194bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700195bool SurfaceFlinger::useContextPriority;
Peiyong Lin0256f722018-08-31 15:45:10 -0700196Dataspace SurfaceFlinger::compositionDataSpace = Dataspace::V0_SRGB;
197ui::PixelFormat SurfaceFlinger::compositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700198
Kalle Raitaa099a242017-01-11 11:17:29 -0800199std::string getHwcServiceName() {
200 char value[PROPERTY_VALUE_MAX] = {};
201 property_get("debug.sf.hwc_service_name", value, "default");
202 ALOGI("Using HWComposer service: '%s'", value);
203 return std::string(value);
204}
205
206bool useTrebleTestingOverride() {
207 char value[PROPERTY_VALUE_MAX] = {};
208 property_get("debug.sf.treble_testing_override", value, "false");
209 ALOGI("Treble testing override: '%s'", value);
210 return std::string(value) == "true";
211}
212
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800213std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
214 switch(displayColorSetting) {
215 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700216 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800217 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700218 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800219 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700220 return std::string("Enhanced");
221 default:
222 return std::string("Unknown ") +
223 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800225}
226
David Sodmanbc815282017-11-05 18:57:52 -0800227SurfaceFlingerBE::SurfaceFlingerBE()
228 : mHwcServiceName(getHwcServiceName()),
229 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800230 mFrameBuckets(),
231 mTotalTime(0),
232 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800233 mComposerSequenceId(0) {
234}
235
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800236SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800237 : BnSurfaceComposer(),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700238 mTransactionPending(false),
239 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700240 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700241 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800242 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700243 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800245 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800246 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800247 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800248 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700249 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700250 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700251 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700252 mDebugInTransaction(0),
253 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700254 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700255 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700256 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800257 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800258 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800259 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700260 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800261 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800262 mCreateBufferQueue(&BufferQueue::createBufferQueue),
Lloyd Pique22098362018-09-13 11:46:49 -0700263 mCreateNativeWindowSurface(&surfaceflinger::impl::createNativeWindowSurface) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800264
265SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800266 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800267
268 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
269 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
270
271 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
272 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
273
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800274 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
275 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700277 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
278 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
279
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700280 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
282
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800283 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
284 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
285
Steven Thomas050b2c82017-03-06 11:45:16 -0800286 // Vr flinger is only enabled on Daydream ready devices.
287 useVrFlinger = getBool< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::useVrFlinger>(false);
289
Fabien Sanglard1971b632017-03-10 14:50:03 -0800290 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
292
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600293 hasWideColorDisplay =
294 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700295 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700296 getBool<V1_2::ISurfaceFlingerConfigs,
297 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
298
299 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
300 if (surfaceFlingerConfigsServiceV1_2) {
301 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
302 [&](Dataspace tmpDataSpace, ui::PixelFormat tmpPixelFormat) {
303 compositionDataSpace = tmpDataSpace;
304 compositionPixelFormat = tmpPixelFormat;
305 });
306 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600307
Peiyong Linb3839ad2018-09-05 15:37:19 -0700308 useContextPriority = getBool<ISurfaceFlingerConfigs,
309 &ISurfaceFlingerConfigs::useContextPriority>(true);
310
Iris Chang7501ed62018-04-30 14:45:42 +0800311 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700312 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
313 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800314 V1_1::DisplayOrientation::ORIENTATION_0);
315
316 switch (primaryDisplayOrientation) {
317 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700318 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800319 break;
320 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700321 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800322 break;
323 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700324 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800325 break;
326 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700327 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800328 break;
329 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700330 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800331
Lloyd Pique41be5d22018-06-21 13:11:48 -0700332 // Note: We create a local temporary with the real DispSync implementation
333 // type temporarily so we can initialize it with the configured values,
334 // before storing it for more generic use using the interface type.
335 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
336 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
337 SurfaceFlinger::dispSyncPresentTimeOffset);
338 mPrimaryDispSync = std::move(primaryDispSync);
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) {
Ana Krulece588e312018-09-18 12:32:24 -0700588 mScheduler = std::make_unique<Scheduler>(
589 [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 Piquea822d522017-12-20 16:42:57 -0800643 getBE().mHwc.reset(
644 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700645 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800646 // Process any initial hotplug and resulting display changes.
647 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700648 const auto display = getDefaultDisplayDeviceLocked();
649 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
650 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
651 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800652
Lloyd Piquefcd86612017-12-14 17:15:36 -0800653 // make the default display GLContext current so that we can create textures
654 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700655 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800656
Steven Thomas050b2c82017-03-06 11:45:16 -0800657 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700658 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700659 // This callback is called from the vr flinger dispatch thread. We
660 // need to call signalTransaction(), which requires holding
661 // mStateLock when we're not on the main thread. Acquiring
662 // mStateLock from the vr flinger dispatch thread might trigger a
663 // deadlock in surface flinger (see b/66916578), so post a message
664 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700665 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700666 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
667 mVrFlingerRequestsDisplay = requestDisplay;
668 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700669 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800670 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700671 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
672 getHwComposer()
673 .getHwcDisplayId(display->getId())
674 .value_or(0),
675 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800676 if (!mVrFlinger) {
677 ALOGE("Failed to start vrflinger");
678 }
679 }
680
Lloyd Pique379adc12018-01-22 17:31:47 -0800681 mEventControlThread = std::make_unique<impl::EventControlThread>(
682 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700683
Mathias Agopian92a979a2012-08-02 18:32:23 -0700684 // initialize our drawing state
685 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700686
Andy McFadden13a082e2012-08-24 10:16:42 -0700687 // set initial conditions (e.g. unblank default device)
688 initializeDisplays();
689
David Sodmanbc815282017-11-05 18:57:52 -0800690 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700691
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692 // Inform native graphics APIs whether the present timestamp is supported:
693 if (getHwComposer().hasCapability(
694 HWC2::Capability::PresentFenceIsNotReliable)) {
695 mStartPropertySetThread = new StartPropertySetThread(false);
696 } else {
697 mStartPropertySetThread = new StartPropertySetThread(true);
698 }
699
700 if (mStartPropertySetThread->Start() != NO_ERROR) {
701 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800702 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800703
Chia-I Wud49d6692018-06-27 07:17:41 +0800704 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
705 // is used to saturate legacy sRGB content. However, to make sure the same color under
706 // Display P3 will be saturated to the same color, we intentionally break the API spec
707 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
708 // such saturation matrix on Display P3 is understood fully, the API should always return
709 // identify matrix.
710 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
711 Dataspace::SRGB_LINEAR);
712
713 // we will apply this on Display P3.
714 if (mEnhancedSaturationMatrix != mat4()) {
715 ColorSpace srgb(ColorSpace::sRGB());
716 ColorSpace displayP3(ColorSpace::DisplayP3());
717 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
718 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
719 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
720 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800721
Dan Stoza9e56aa02015-11-02 13:00:03 -0800722 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700723}
724
Romain Guy11d63f42017-07-20 12:47:14 -0700725void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700726 Mutex::Autolock _l(mStateLock);
727
Romain Guy11d63f42017-07-20 12:47:14 -0700728 char value[PROPERTY_VALUE_MAX];
729
730 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800731 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700732 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800733 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100734
735 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700736 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700737}
738
Mathias Agopiana67e4182012-06-19 17:26:12 -0700739void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800740 // Start boot animation service by setting a property mailbox
741 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700742 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800743 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744 if (mStartPropertySetThread->join() != NO_ERROR) {
745 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800746 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700747}
748
Mathias Agopian875d8e12013-06-07 15:35:48 -0700749size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800750 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700751}
752
Mathias Agopian875d8e12013-06-07 15:35:48 -0700753size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800754 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700755}
756
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800757// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800758
Jamie Gennis582270d2011-08-17 18:19:00 -0700759bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800760 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800761 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800762 return authenticateSurfaceTextureLocked(bufferProducer);
763}
764
765bool SurfaceFlinger::authenticateSurfaceTextureLocked(
766 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800767 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800768 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800769}
770
Brian Anderson6b376712017-04-04 10:51:39 -0700771status_t SurfaceFlinger::getSupportedFrameTimestamps(
772 std::vector<FrameEvent>* outSupported) const {
773 *outSupported = {
774 FrameEvent::REQUESTED_PRESENT,
775 FrameEvent::ACQUIRE,
776 FrameEvent::LATCH,
777 FrameEvent::FIRST_REFRESH_START,
778 FrameEvent::LAST_REFRESH_START,
779 FrameEvent::GPU_COMPOSITION_DONE,
780 FrameEvent::DEQUEUE_READY,
781 FrameEvent::RELEASE,
782 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700783 ConditionalLock _l(mStateLock,
784 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700785 if (!getHwComposer().hasCapability(
786 HWC2::Capability::PresentFenceIsNotReliable)) {
787 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
788 }
789 return NO_ERROR;
790}
791
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700792status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
793 Vector<DisplayInfo>* configs) {
794 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700795 return BAD_VALUE;
796 }
797
Jesse Hall692c7232012-11-08 15:41:56 -0800798 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700799 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
800 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700801 type = i;
802 break;
803 }
804 }
805
806 if (type < 0) {
807 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700808 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700809
Mathias Agopian8b736f12012-08-13 17:54:26 -0700810 // TODO: Not sure if display density should handled by SF any longer
811 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700812 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700813 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700814 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800815 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700816 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817 }
818 return density;
819 }
820 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700821 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700823 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 return getDensityFromProperty("ro.sf.lcd_density"); }
825 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700826
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700828
Steven Thomas6d8110b2017-08-31 18:24:21 -0700829 ConditionalLock _l(mStateLock,
830 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800831 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700832 DisplayInfo info = DisplayInfo();
833
Dan Stoza9e56aa02015-11-02 13:00:03 -0800834 float xdpi = hwConfig->getDpiX();
835 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700836
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700837 info.w = hwConfig->getWidth();
838 info.h = hwConfig->getHeight();
839 // Default display viewport to display width and height
840 info.viewportW = info.w;
841 info.viewportH = info.h;
842
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 if (type == DisplayDevice::DISPLAY_PRIMARY) {
844 // The density of the device is provided by a build property
845 float density = Density::getBuildDensity() / 160.0f;
846 if (density == 0) {
847 // the build doesn't provide a density -- this is wrong!
848 // use xdpi instead
849 ALOGE("ro.sf.lcd_density must be defined as a build property");
850 density = xdpi / 160.0f;
851 }
852 if (Density::getEmuDensity()) {
853 // if "qemu.sf.lcd_density" is specified, it overrides everything
854 xdpi = ydpi = density = Density::getEmuDensity();
855 density /= 160.0f;
856 }
857 info.density = density;
858
859 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700860 const auto display = getDefaultDisplayDeviceLocked();
861 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700862
863 // This is for screenrecord
864 const Rect viewport = display->getViewport();
865 if (viewport.isValid()) {
866 info.viewportW = uint32_t(viewport.getWidth());
867 info.viewportH = uint32_t(viewport.getHeight());
868 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 } else {
870 // TODO: where should this value come from?
871 static const int TV_DENSITY = 213;
872 info.density = TV_DENSITY / 160.0f;
873 info.orientation = 0;
874 }
875
Dan Stoza7f7da322014-05-02 15:26:25 -0700876 info.xdpi = xdpi;
877 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800878 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900879 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800880
Andy McFadden91b2ca82014-06-13 14:04:23 -0700881 // This is how far in advance a buffer must be queued for
882 // presentation at a given time. If you want a buffer to appear
883 // on the screen at time N, you must submit the buffer before
884 // (N - presentationDeadline).
885 //
886 // Normally it's one full refresh period (to give SF a chance to
887 // latch the buffer), but this can be reduced by configuring a
888 // DispSync offset. Any additional delays introduced by the hardware
889 // composer or panel must be accounted for here.
890 //
891 // We add an additional 1ms to allow for processing time and
892 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800893 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800894 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700895
896 // All non-virtual displays are currently considered secure.
897 info.secure = true;
898
Iris Chang7501ed62018-04-30 14:45:42 +0800899 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700900 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800901 std::swap(info.w, info.h);
902 }
903
Michael Wright28f24d02016-07-12 13:30:53 -0700904 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700905 }
906
Dan Stoza7f7da322014-05-02 15:26:25 -0700907 return NO_ERROR;
908}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700909
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700910status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
911 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700912 return BAD_VALUE;
913 }
914
Ana Krulece588e312018-09-18 12:32:24 -0700915 // FIXME for now we always return stats for the primary display.
916 if (mUseScheduler) {
917 mScheduler->getDisplayStatInfo(stats);
918 } else {
919 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
920 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
921 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700922 return NO_ERROR;
923}
924
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700925int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
926 const auto display = getDisplayDevice(displayToken);
927 if (!display) {
928 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800929 return BAD_VALUE;
930 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700933}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
936 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700937 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700938 return;
939 }
940
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700941 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700942 ALOGW("Trying to set config for virtual display");
943 return;
944 }
945
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700946 display->setActiveConfig(mode);
947 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700948}
949
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700950status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700951 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700952 Vector<DisplayInfo> configs;
953 getDisplayConfigs(displayToken, &configs);
954 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
955 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
956 configs.size());
957 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700958 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700959 const auto display = getDisplayDevice(displayToken);
960 if (!display) {
961 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
962 displayToken.get());
963 } else if (display->isVirtual()) {
964 ALOGW("Attempt to set active config %d for virtual display", mode);
965 } else {
966 setActiveConfigInternal(display, mode);
967 }
968 }));
969
Mathias Agopian888c8222012-08-04 21:10:38 -0700970 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700971}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700972status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
973 Vector<ColorMode>* outColorModes) {
974 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700975 return BAD_VALUE;
976 }
977
Michael Wright28f24d02016-07-12 13:30:53 -0700978 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700979 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
980 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700981 type = i;
982 break;
983 }
984 }
985
986 if (type < 0) {
987 return type;
988 }
989
Peiyong Lina52f0292018-03-14 17:26:31 -0700990 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700991 {
992 ConditionalLock _l(mStateLock,
993 std::this_thread::get_id() != mMainThreadId);
994 modes = getHwComposer().getColorModes(type);
995 }
Michael Wright28f24d02016-07-12 13:30:53 -0700996 outColorModes->clear();
997 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
998
999 return NO_ERROR;
1000}
1001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001002ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1003 if (const auto display = getDisplayDevice(displayToken)) {
1004 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001005 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001006 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001007}
1008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1010 Dataspace dataSpace, RenderIntent renderIntent) {
1011 ColorMode currentMode = display->getActiveColorMode();
1012 Dataspace currentDataSpace = display->getCompositionDataSpace();
1013 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001014
Peiyong Lin38e9a562018-04-10 16:24:20 -07001015 if (mode == currentMode && dataSpace == currentDataSpace &&
1016 renderIntent == currentRenderIntent) {
1017 return;
1018 }
1019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001020 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001021 ALOGW("Trying to set config for virtual display");
1022 return;
1023 }
1024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025 display->setActiveColorMode(mode);
1026 display->setCompositionDataSpace(dataSpace);
1027 display->setActiveRenderIntent(renderIntent);
1028 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001029
1030 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1032 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001033}
1034
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001035status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001036 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001037 Vector<ColorMode> modes;
1038 getDisplayColorModes(displayToken, &modes);
1039 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1040 if (mode < ColorMode::NATIVE || !exists) {
1041 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1042 decodeColorMode(mode).c_str(), mode, displayToken.get());
1043 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001044 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001045 const auto display = getDisplayDevice(displayToken);
1046 if (!display) {
1047 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1048 decodeColorMode(mode).c_str(), mode, displayToken.get());
1049 } else if (display->isVirtual()) {
1050 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1051 decodeColorMode(mode).c_str(), mode);
1052 } else {
1053 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1054 RenderIntent::COLORIMETRIC);
1055 }
1056 }));
1057
Michael Wright28f24d02016-07-12 13:30:53 -07001058 return NO_ERROR;
1059}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001060
Svetoslavd85084b2014-03-20 10:28:31 -07001061status_t SurfaceFlinger::clearAnimationFrameStats() {
1062 Mutex::Autolock _l(mStateLock);
1063 mAnimFrameTracker.clearStats();
1064 return NO_ERROR;
1065}
1066
1067status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1068 Mutex::Autolock _l(mStateLock);
1069 mAnimFrameTracker.getStats(outStats);
1070 return NO_ERROR;
1071}
1072
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001073status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1074 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001075 Mutex::Autolock _l(mStateLock);
1076
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001077 const auto display = getDisplayDeviceLocked(displayToken);
1078 if (!display) {
1079 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001080 return BAD_VALUE;
1081 }
1082
Peiyong Linfb069302018-04-25 14:34:31 -07001083 // At this point the DisplayDeivce should already be set up,
1084 // meaning the luminance information is already queried from
1085 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001087 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1088 capabilities.getDesiredMaxLuminance(),
1089 capabilities.getDesiredMaxAverageLuminance(),
1090 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001091
1092 return NO_ERROR;
1093}
1094
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001095status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001096 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001097 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001098
Chia-I Wu90f669f2017-10-05 14:24:41 -07001099 if (mInjectVSyncs == enable) {
1100 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001101 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001102
Ana Krulec98b5b242018-08-10 15:03:23 -07001103 // TODO(akrulec): Part of the Injector should be refactored, so that it
1104 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001105 if (enable) {
1106 ALOGV("VSync Injections enabled");
1107 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001108 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001109 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001110 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001111 impl::EventThread::InterceptVSyncsCallback(),
1112 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001113 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001114 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 } else {
1116 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001117 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001118 }
1119
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001120 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001121 }));
1122
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001123 return NO_ERROR;
1124}
1125
1126status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001127 Mutex::Autolock _l(mStateLock);
1128
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001129 if (!mInjectVSyncs) {
1130 ALOGE("VSync Injections not enabled");
1131 return BAD_VALUE;
1132 }
1133 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1134 ALOGV("Injecting VSync inside SurfaceFlinger");
1135 mVSyncInjector->onInjectSyncEvent(when);
1136 }
1137 return NO_ERROR;
1138}
1139
Lloyd Pique755e3192018-01-31 16:46:15 -08001140status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1141 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001142 // Try to acquire a lock for 1s, fail gracefully
1143 const status_t err = mStateLock.timedLock(s2ns(1));
1144 const bool locked = (err == NO_ERROR);
1145 if (!locked) {
1146 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1147 return TIMED_OUT;
1148 }
1149
1150 outLayers->clear();
1151 mCurrentState.traverseInZOrder([&](Layer* layer) {
1152 outLayers->push_back(layer->getLayerDebugInfo());
1153 });
1154
1155 mStateLock.unlock();
1156 return NO_ERROR;
1157}
1158
Peiyong Lin0256f722018-08-31 15:45:10 -07001159status_t SurfaceFlinger::getCompositionPreference(Dataspace* outDataSpace,
1160 ui::PixelFormat* outPixelFormat) const {
1161 *outDataSpace = compositionDataSpace;
1162 *outPixelFormat = compositionPixelFormat;
1163 return NO_ERROR;
1164}
1165
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001166// ----------------------------------------------------------------------------
1167
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001168sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1169 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001170 if (mUseScheduler) {
1171 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1172 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1173 } else {
1174 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1175 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001176 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001177 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1178 return mSFEventThread->createEventConnection();
1179 } else {
1180 return mEventThread->createEventConnection();
1181 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001182 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001183}
1184
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001185// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001186
1187void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001188 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001189}
1190
1191void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001192 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001193}
1194
1195void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001196 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001197}
1198
1199void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001200 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001201 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001202}
1203
1204status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001205 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001206 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001207}
1208
1209status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001210 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001211 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001212 if (res == NO_ERROR) {
1213 msg->wait();
1214 }
1215 return res;
1216}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001217
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001218void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001219 do {
1220 waitForEvent();
1221 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001222}
1223
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001224void SurfaceFlinger::enableHardwareVsync() {
1225 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001226 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001227 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001228 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001229 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001230 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001231}
1232
Jesse Hall948fe0c2013-10-14 12:56:09 -07001233void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001234 Mutex::Autolock _l(mHWVsyncLock);
1235
Jesse Hall948fe0c2013-10-14 12:56:09 -07001236 if (makeAvailable) {
1237 mHWVsyncAvailable = true;
1238 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001239 // Hardware vsync is not currently available, so abort the resync
1240 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001241 return;
1242 }
1243
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001244 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1245 if (!getHwComposer().isConnected(displayId)) {
1246 return;
1247 }
1248
1249 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001250 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251
Ana Krulece588e312018-09-18 12:32:24 -07001252 if (mUseScheduler) {
1253 mScheduler->setVsyncPeriod(period);
1254 } else {
1255 mPrimaryDispSync->reset();
1256 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001257
Ana Krulece588e312018-09-18 12:32:24 -07001258 if (!mPrimaryHWVsyncEnabled) {
1259 mPrimaryDispSync->beginResync();
1260 mEventControlThread->setVsyncEnabled(true);
1261 mPrimaryHWVsyncEnabled = true;
1262 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001263 }
1264}
1265
Jesse Hall948fe0c2013-10-14 12:56:09 -07001266void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267 Mutex::Autolock _l(mHWVsyncLock);
1268 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001269 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001270 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001271 mPrimaryHWVsyncEnabled = false;
1272 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001273 if (makeUnavailable) {
1274 mHWVsyncAvailable = false;
1275 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001276}
1277
Tim Murray4a4e4a22016-04-19 16:29:23 +00001278void SurfaceFlinger::resyncWithRateLimit() {
1279 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001280
1281 // No explicit locking is needed here since EventThread holds a lock while calling this method
1282 static nsecs_t sLastResyncAttempted = 0;
1283 const nsecs_t now = systemTime();
1284 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001285 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001286 }
Dan Stoza57164302017-05-08 14:03:54 -07001287 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001288}
1289
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001290void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1291 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001292 ATRACE_NAME("SF onVsync");
1293
Steven Thomas3cfac282017-02-06 12:29:30 -08001294 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001295 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001296 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001297 return;
1298 }
1299
1300 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001301 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001302 return;
1303 }
1304
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001305 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1306 // For now, we don't do anything with external display vsyncs.
1307 return;
1308 }
1309
Ana Krulece588e312018-09-18 12:32:24 -07001310 if (mUseScheduler) {
1311 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001312 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001313 bool needsHwVsync = false;
1314 { // Scope for the lock
1315 Mutex::Autolock _l(mHWVsyncLock);
1316 if (mPrimaryHWVsyncEnabled) {
1317 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1318 }
1319 }
1320
1321 if (needsHwVsync) {
1322 enableHardwareVsync();
1323 } else {
1324 disableHardwareVsync(false);
1325 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001326 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001327}
1328
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001329void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001330 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1331 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001332}
1333
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001334void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001335 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001336 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001337 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001338
Lloyd Piqueba04e622017-12-14 17:11:26 -08001339 // Ignore events that do not have the right sequenceId.
1340 if (sequenceId != getBE().mComposerSequenceId) {
1341 return;
1342 }
1343
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 // Only lock if we're not on the main thread. This function is normally
1345 // called on a hwbinder thread, but for the primary display it's called on
1346 // the main thread with the state lock already held, so don't attempt to
1347 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001348 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001349
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001350 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001351
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001352 if (std::this_thread::get_id() == mMainThreadId) {
1353 // Process all pending hot plug events immediately if we are on the main thread.
1354 processDisplayHotplugEventsLocked();
1355 }
1356
Lloyd Piqueba04e622017-12-14 17:11:26 -08001357 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001358}
1359
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001360void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001361 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001362 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001363 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001364 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001365 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001366}
1367
Dan Stoza9e56aa02015-11-02 13:00:03 -08001368void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001369 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001370 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001371 getHwComposer().setVsyncEnabled(disp,
1372 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001373}
1374
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001375// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001376void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001377 if (mUseScheduler) {
1378 mScheduler->disableHardwareVsync(true);
1379 } else {
1380 disableHardwareVsync(true);
1381 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001382 // Clear the drawing state so that the logic inside of
1383 // handleTransactionLocked will fire. It will determine the delta between
1384 // mCurrentState and mDrawingState and re-apply all changes when we make the
1385 // transition.
1386 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001387 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001388 mDisplays.clear();
1389}
1390
Steven Thomas050b2c82017-03-06 11:45:16 -08001391void SurfaceFlinger::updateVrFlinger() {
1392 if (!mVrFlinger)
1393 return;
1394 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001395 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001396 return;
1397 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001398
David Sodman105b7dc2017-11-04 20:28:14 -07001399 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 ALOGE("Vr flinger is only supported for remote hardware composer"
1401 " service connections. Ignoring request to transition to vr"
1402 " flinger.");
1403 mVrFlingerRequestsDisplay = false;
1404 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001405 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001406
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001407 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001408
Steven Thomas0123ac62018-07-12 11:32:34 -07001409 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001410 LOG_ALWAYS_FATAL_IF(!display);
1411 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001412 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1413 // called below. Clear the reference now so we don't accidentally use it
1414 // later.
1415 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416
Steven Thomasb02664d2017-07-26 18:48:28 -07001417 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001418 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001420
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001422 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001423 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1424 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001425 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001426
David Sodman105b7dc2017-11-04 20:28:14 -07001427 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1428 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001429
1430 if (vrFlingerRequestsDisplay) {
1431 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001432 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001433
1434 mVisibleRegionsDirty = true;
1435 invalidateHwcGeometry();
1436
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001437 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001438 display = getDefaultDisplayDeviceLocked();
1439 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001440 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001441
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001443 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 const nsecs_t period = activeConfig->getVsyncPeriod();
1445 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001446
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001447 // The present fences returned from vr_hwc are not an accurate
1448 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001449 if (mUseScheduler) {
1450 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1451 } else {
1452 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1453 !hasSyncFramework);
1454 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001455
Steven Thomasb02664d2017-07-26 18:48:28 -07001456 // Use phase of 0 since phase is not known.
1457 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001458 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1459 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001460
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001461 resyncToHardwareVsync(false);
1462
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001463 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001464 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001465}
1466
Mathias Agopian4fec8732012-06-29 14:12:52 -07001467void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001468 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001469 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001470 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001471 bool frameMissed = !mHadClientComposition &&
1472 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001473 (mPreviousPresentFence->getSignalTime() ==
1474 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001475 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001476 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001477 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001478 mTimeStats.incrementMissedFrames();
1479 if (mPropagateBackpressure) {
1480 signalLayerUpdate();
1481 break;
1482 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001483 }
Dan Stoza50182882016-07-08 12:02:20 -07001484
Steven Thomas050b2c82017-03-06 11:45:16 -08001485 // Now that we're going to make it to the handleMessageTransaction()
1486 // call below it's safe to call updateVrFlinger(), which will
1487 // potentially trigger a display handoff.
1488 updateVrFlinger();
1489
Dan Stoza6b9454d2014-11-07 16:00:59 -08001490 bool refreshNeeded = handleMessageTransaction();
1491 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001492 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001493 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001494 // Signal a refresh if a transaction modified the window state,
1495 // a new buffer was latched, or if HWC has requested a full
1496 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001497 signalRefresh();
1498 }
1499 break;
1500 }
1501 case MessageQueue::REFRESH: {
1502 handleMessageRefresh();
1503 break;
1504 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001505 }
1506}
1507
Dan Stoza6b9454d2014-11-07 16:00:59 -08001508bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001509 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001510 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001511 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001512 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001513 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001514 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001515}
1516
Mathias Agopian4fec8732012-06-29 14:12:52 -07001517void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001518 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001519
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001520 mRefreshPending = false;
1521
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001522 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001523 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001524 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001525 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001526 for (const auto& [token, display] : mDisplays) {
1527 beginFrame(display);
1528 prepareFrame(display);
1529 doDebugFlashRegions(display, repaintEverything);
1530 doComposition(display, repaintEverything);
1531 }
1532
Adrian Roos1e1a1282017-11-01 19:05:31 +01001533 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001534 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001535
1536 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001537 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001538
Dan Stozabfbffeb2016-07-21 14:49:33 -07001539 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001540 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001541 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001542 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001543 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001544
Alec Mouri86770e52018-09-24 22:40:58 +00001545 // Setup RenderEngine sync fences if native sync is supported.
1546 if (getBE().mRenderEngine->useNativeFenceSync()) {
1547 if (mHadClientComposition) {
1548 base::unique_fd flushFence(getRenderEngine().flush());
1549 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1550 getBE().flushFence = new Fence(std::move(flushFence));
1551 } else {
1552 // Cleanup for hygiene.
1553 getBE().flushFence = Fence::NO_FENCE;
1554 }
1555 }
1556
Jorim Jaggi90535212018-05-23 23:44:06 +02001557 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001558
David Sodman7e4ae112018-02-09 15:02:28 -08001559 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001560 for (const auto& [token, display] : mDisplays) {
1561 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001562 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001563 compositionInfo.hwc.hwcLayer = nullptr;
1564 }
David Sodmanba340492018-08-05 21:51:33 -07001565 }
David Sodman7e4ae112018-02-09 15:02:28 -08001566
1567 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001568}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001569
David Sodmanfa9b2af2017-12-24 13:28:59 -08001570
1571bool SurfaceFlinger::handleMessageInvalidate() {
1572 ATRACE_CALL();
1573 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001574}
1575
David Sodman79bba0e2018-08-05 18:07:49 -07001576void SurfaceFlinger::calculateWorkingSet() {
1577 ATRACE_CALL();
1578 ALOGV(__FUNCTION__);
1579
David Sodman79bba0e2018-08-05 18:07:49 -07001580 // build the h/w work list
1581 if (CC_UNLIKELY(mGeometryInvalid)) {
1582 mGeometryInvalid = false;
1583 for (const auto& [token, display] : mDisplays) {
1584 const auto displayId = display->getId();
1585 if (displayId >= 0) {
1586 const Vector<sp<Layer>>& currentLayers(
1587 display->getVisibleLayersSortedByZ());
1588 for (size_t i = 0; i < currentLayers.size(); i++) {
1589 const auto& layer = currentLayers[i];
1590
1591 if (!layer->hasHwcLayer(displayId)) {
1592 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1593 layer->forceClientComposition(displayId);
1594 continue;
1595 }
1596 }
1597
1598 layer->setGeometry(display, i);
1599 if (mDebugDisableHWC || mDebugRegion) {
1600 layer->forceClientComposition(displayId);
1601 }
1602 }
1603 }
1604 }
1605 }
1606
1607 // Set the per-frame data
1608 for (const auto& [token, display] : mDisplays) {
1609 const auto displayId = display->getId();
1610 if (displayId < 0) {
1611 continue;
1612 }
1613
1614 if (mDrawingState.colorMatrixChanged) {
1615 display->setColorTransform(mDrawingState.colorMatrix);
1616 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1617 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1618 "display %d: %d", displayId, result);
1619 }
1620 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1621 if (layer->isHdrY410()) {
1622 layer->forceClientComposition(displayId);
1623 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1624 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1625 !display->hasHDR10Support()) {
1626 layer->forceClientComposition(displayId);
1627 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1628 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1629 !display->hasHLGSupport()) {
1630 layer->forceClientComposition(displayId);
1631 }
1632
Peiyong Lind3788632018-09-18 16:01:31 -07001633 // TODO(b/111562338) remove when composer 2.3 is shipped.
1634 if (layer->hasColorTransform()) {
1635 layer->forceClientComposition(displayId);
1636 }
1637
David Sodman79bba0e2018-08-05 18:07:49 -07001638 if (layer->getForceClientComposition(displayId)) {
1639 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1640 layer->setCompositionType(displayId, HWC2::Composition::Client);
1641 continue;
1642 }
1643
1644 layer->setPerFrameData(display);
1645 }
1646
Peiyong Lin13effd12018-07-24 17:01:47 -07001647 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001648 ColorMode colorMode;
1649 Dataspace dataSpace;
1650 RenderIntent renderIntent;
1651 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1652 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1653 }
1654 }
1655
1656 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001657
1658 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001659 const auto displayId = display->getId();
1660 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001661 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1662 auto displayId = display->getId();
1663 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1664 if (!layer->setHwcLayer(displayId)) {
1665 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1666 }
David Sodman15fb96e2018-01-07 10:23:24 -08001667 layer->getBE().compositionInfo.hwc.displayId = displayId;
1668 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001669 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1670 }
1671 }
David Sodman79bba0e2018-08-05 18:07:49 -07001672}
1673
David Sodmanfa9b2af2017-12-24 13:28:59 -08001674void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001675{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001676 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001677 // is debugging enabled
1678 if (CC_LIKELY(!mDebugRegion))
1679 return;
1680
David Sodmanfa9b2af2017-12-24 13:28:59 -08001681 if (display->isPoweredOn()) {
1682 // transform the dirty region into this screen's coordinate space
1683 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1684 if (!dirtyRegion.isEmpty()) {
1685 // redraw the whole screen
1686 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001687
David Sodmanfa9b2af2017-12-24 13:28:59 -08001688 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001689 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001690 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001691
David Sodmanfa9b2af2017-12-24 13:28:59 -08001692 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693 }
1694 }
1695
David Sodmanfa9b2af2017-12-24 13:28:59 -08001696 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001697
1698 if (mDebugRegion > 1) {
1699 usleep(mDebugRegion * 1000);
1700 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001701
David Sodmanfa9b2af2017-12-24 13:28:59 -08001702 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001703 status_t result = display->prepareFrame(
1704 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001705 ALOGE_IF(result != NO_ERROR,
1706 "prepareFrame for display %d failed:"
1707 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001708 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001709 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001710}
1711
Adrian Roos1e1a1282017-11-01 19:05:31 +01001712void SurfaceFlinger::doTracing(const char* where) {
1713 ATRACE_CALL();
1714 ATRACE_NAME(where);
1715 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001716 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001717 }
1718}
1719
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001720void SurfaceFlinger::logLayerStats() {
1721 ATRACE_CALL();
1722 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001723 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001724 if (display->isPrimary()) {
1725 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001726 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001727 }
1728 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001729
1730 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001731 }
1732}
1733
David Sodman2b406362017-12-15 13:33:47 -08001734void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001735{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001736 ATRACE_CALL();
1737 ALOGV("preComposition");
1738
David Sodman2b406362017-12-15 13:33:47 -08001739 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1740
Mathias Agopiancd60f992012-08-16 16:28:27 -07001741 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001742 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001743 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001744 needExtraInvalidate = true;
1745 }
Robert Carr2047fae2016-11-28 14:09:09 -08001746 });
1747
Mathias Agopiancd60f992012-08-16 16:28:27 -07001748 if (needExtraInvalidate) {
1749 signalLayerUpdate();
1750 }
1751}
1752
Ana Krulece588e312018-09-18 12:32:24 -07001753void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1754 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001755 // Update queue of past composite+present times and determine the
1756 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001757 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001758 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001759 while (!getBE().mCompositePresentTimes.empty()) {
1760 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001761 // Cached values should have been updated before calling this method,
1762 // which helps avoid duplicate syscalls.
1763 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1764 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1765 break;
1766 }
1767 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001768 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001769 }
1770
1771 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001772 while (getBE().mCompositePresentTimes.size() > 16) {
1773 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001774 }
1775
Ana Krulece588e312018-09-18 12:32:24 -07001776 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001777}
1778
Ana Krulece588e312018-09-18 12:32:24 -07001779void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1780 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001781 // Integer division and modulo round toward 0 not -inf, so we need to
1782 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001783 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1784 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1785 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001786
Brian Andersond0010582017-03-07 13:20:31 -08001787 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1788 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001789 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001790 }
1791
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001792 // Snap the latency to a value that removes scheduling jitter from the
1793 // composition and present times, which often have >1ms of jitter.
1794 // Reducing jitter is important if an app attempts to extrapolate
1795 // something (such as user input) to an accurate diasplay time.
1796 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1797 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001798 nsecs_t bias = stats.vsyncPeriod / 2;
1799 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1800 nsecs_t snappedCompositeToPresentLatency =
1801 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001802
David Sodman99974d22017-11-28 12:04:33 -08001803 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001804 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1805 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001806 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001807}
1808
David Sodman2b406362017-12-15 13:33:47 -08001809void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001810{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001811 ATRACE_CALL();
1812 ALOGV("postComposition");
1813
Brian Anderson3546a3f2016-07-14 11:51:14 -07001814 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001815 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001816 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001817 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001818 }
1819
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001820 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001821 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001822
David Sodman73beded2017-11-15 11:56:06 -08001823 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001824 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001825 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001826 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001827 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001828 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001829 } else {
1830 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1831 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001832
David Sodman73beded2017-11-15 11:56:06 -08001833 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001834 mPreviousPresentFence =
1835 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1836 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001837 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001838
Ana Krulece588e312018-09-18 12:32:24 -07001839 DisplayStatInfo stats;
1840 if (mUseScheduler) {
1841 mScheduler->getDisplayStatInfo(&stats);
1842 } else {
1843 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1844 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1845 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001846
David Sodman2b406362017-12-15 13:33:47 -08001847 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001848 // when we started doing work for this frame, but that should be okay
1849 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001850 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001851 CompositorTiming compositorTiming;
1852 {
David Sodman99974d22017-11-28 12:04:33 -08001853 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1854 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001855 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001856
Robert Carr2047fae2016-11-28 14:09:09 -08001857 mDrawingState.traverseInZOrder([&](Layer* layer) {
1858 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001859 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001860 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001861 recordBufferingStats(layer->getName().string(),
1862 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001863 }
Robert Carr2047fae2016-11-28 14:09:09 -08001864 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001865
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001866 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001867 if (mUseScheduler) {
1868 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001869 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001870 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1871 enableHardwareVsync();
1872 } else {
1873 disableHardwareVsync(false);
1874 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001875 }
1876 }
1877
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001878 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001879 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001880 if (mUseScheduler) {
1881 mScheduler->enableHardwareVsync();
1882 } else {
1883 enableHardwareVsync();
1884 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001885 }
1886 }
1887
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001888 if (mAnimCompositionPending) {
1889 mAnimCompositionPending = false;
1890
Brian Anderson4e606e32017-03-16 15:34:57 -07001891 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001892 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001893 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001894 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001895 // The HWC doesn't support present fences, so use the refresh
1896 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001897 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001898 mAnimFrameTracker.setActualPresentTime(presentTime);
1899 }
1900 mAnimFrameTracker.advanceFrame();
1901 }
Dan Stozab90cf072015-03-05 11:05:59 -08001902
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001903 mTimeStats.incrementTotalFrames();
1904 if (mHadClientComposition) {
1905 mTimeStats.incrementClientCompositionFrames();
1906 }
1907
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001908 mTimeStats.setPresentFenceGlobal(presentFenceTime);
1909
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001910 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001911 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001912 return;
1913 }
1914
1915 nsecs_t currentTime = systemTime();
1916 if (mHasPoweredOff) {
1917 mHasPoweredOff = false;
1918 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001919 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001920 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001921 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1922 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001923 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001924 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001925 }
David Sodman4a36e932017-11-07 14:29:47 -08001926 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001927 }
David Sodman4a36e932017-11-07 14:29:47 -08001928 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001929
1930 {
1931 std::lock_guard lock(mTexturePoolMutex);
1932 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1933 if (refillCount > 0) {
1934 const size_t offset = mTexturePool.size();
1935 mTexturePool.resize(mTexturePoolSize);
1936 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1937 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1938 }
1939 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001940}
1941
1942void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001943 ATRACE_CALL();
1944 ALOGV("rebuildLayerStacks");
1945
Mathias Agopiancd60f992012-08-16 16:28:27 -07001946 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001947 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001948 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001949 mVisibleRegionsDirty = false;
1950 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001951
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001952 for (const auto& pair : mDisplays) {
1953 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001954 Region opaqueRegion;
1955 Region dirtyRegion;
1956 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001957 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001958 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001959 const Rect bounds = display->getBounds();
1960 if (display->isPoweredOn()) {
1961 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001962
Jeff Sharkey76488112017-02-27 14:15:18 -07001963 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001964 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001965 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001966 Region drawRegion(tr.transform(
1967 layer->visibleNonTransparentRegion));
1968 drawRegion.andSelf(bounds);
1969 if (!drawRegion.isEmpty()) {
1970 layersSortedByZ.add(layer);
1971 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001972 // Clear out the HWC layer if this layer was
1973 // previously visible, but no longer is
1974 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001975 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001976 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001977 // WM changes display->layerStack upon sleep/awake.
1978 // Here we make sure we delete the HWC layers even if
1979 // WM changed their layer stack.
1980 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001981 }
1982
1983 // If a layer is not going to get a release fence because
1984 // it is invisible, but it is also going to release its
1985 // old buffer, add it to the list of layers needing
1986 // fences.
1987 if (hwcLayerDestroyed) {
1988 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1989 mLayersWithQueuedFrames.cend(), layer);
1990 if (found != mLayersWithQueuedFrames.cend()) {
1991 layersNeedingFences.add(layer);
1992 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001993 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001994 });
1995 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001996 display->setVisibleLayersSortedByZ(layersSortedByZ);
1997 display->setLayersNeedingFences(layersNeedingFences);
1998 display->undefinedRegion.set(bounds);
1999 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2000 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002001 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002002 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002003}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002004
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002005// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002006// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002007// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002008// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002009// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002010// The returned HDR data space is one of
2011// - Dataspace::UNKNOWN
2012// - Dataspace::BT2020_HLG
2013// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002014Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2015 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002016 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002017 *outHdrDataSpace = Dataspace::UNKNOWN;
2018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002019 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002020 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002021 case Dataspace::V0_SCRGB:
2022 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002023 case Dataspace::BT2020:
2024 case Dataspace::BT2020_ITU:
2025 case Dataspace::BT2020_LINEAR:
2026 case Dataspace::DISPLAY_BT2020:
2027 bestDataSpace = Dataspace::DISPLAY_BT2020;
2028 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002029 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002030 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002031 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002032 case Dataspace::BT2020_PQ:
2033 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002034 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002035 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002036 case Dataspace::BT2020_HLG:
2037 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002038 // When there's mixed PQ content and HLG content, we set the HDR
2039 // data space to be BT2020_PQ and convert HLG to PQ.
2040 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2041 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002042 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002043 break;
2044 default:
2045 break;
2046 }
Romain Guy54f154a2017-10-24 21:40:32 +01002047 }
2048
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002049 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002050}
2051
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002052// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002053void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2054 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002055 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2056 *outMode = ColorMode::NATIVE;
2057 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002058 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002059 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002060 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002061
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002062 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002063 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002064
Peiyong Lindfde5112018-06-05 10:58:41 -07002065 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002066 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002067 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002068 if (isHdr) {
2069 bestDataSpace = hdrDataSpace;
2070 }
2071
Chia-I Wu0d711262018-05-21 15:19:35 -07002072 RenderIntent intent;
2073 switch (mDisplayColorSetting) {
2074 case DisplayColorSetting::MANAGED:
2075 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002076 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002077 break;
2078 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002079 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002080 break;
2081 default: // vendor display color setting
2082 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2083 break;
2084 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002086 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002087}
2088
David Sodmanfa9b2af2017-12-24 13:28:59 -08002089void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002090{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002091 bool dirty = !display->getDirtyRegion(false).isEmpty();
2092 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2093 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002094
David Sodmanfa9b2af2017-12-24 13:28:59 -08002095 // If nothing has changed (!dirty), don't recompose.
2096 // If something changed, but we don't currently have any visible layers,
2097 // and didn't when we last did a composition, then skip it this time.
2098 // The second rule does two things:
2099 // - When all layers are removed from a display, we'll emit one black
2100 // frame, then nothing more until we get new layers.
2101 // - When a display is created with a private layer stack, we won't
2102 // emit any black frames until a layer is added to the layer stack.
2103 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002104
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002105 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2106 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002107 mustRecompose ? "doing" : "skipping",
2108 dirty ? "+" : "-",
2109 empty ? "+" : "-",
2110 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002111
David Sodmanfa9b2af2017-12-24 13:28:59 -08002112 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002113
David Sodmanfa9b2af2017-12-24 13:28:59 -08002114 if (mustRecompose) {
2115 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002116 }
2117}
2118
David Sodmanfa9b2af2017-12-24 13:28:59 -08002119void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002120{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002121 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002122 if (!display->isPoweredOn()) {
2123 return;
David Sodman2b406362017-12-15 13:33:47 -08002124 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002125
David Sodmanfb95bcc2017-12-22 15:45:30 -08002126 status_t result = display->prepareFrame(
2127 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002128 ALOGE_IF(result != NO_ERROR,
2129 "prepareFrame for display %d failed:"
2130 " %d (%s)",
2131 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002132}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002133
David Sodmanfa9b2af2017-12-24 13:28:59 -08002134void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002135 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002136 ALOGV("doComposition");
2137
David Sodmanfa9b2af2017-12-24 13:28:59 -08002138 if (display->isPoweredOn()) {
2139 // transform the dirty region into this screen's coordinate space
2140 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002141
David Sodmanfa9b2af2017-12-24 13:28:59 -08002142 // repaint the framebuffer (if needed)
2143 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002144
David Sodmanfa9b2af2017-12-24 13:28:59 -08002145 display->dirtyRegion.clear();
2146 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002147 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002148 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002149}
2150
David Sodmanfa9b2af2017-12-24 13:28:59 -08002151void SurfaceFlinger::postFrame()
2152{
2153 // |mStateLock| not needed as we are on the main thread
2154 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2155 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2156 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2157 logFrameStats();
2158 }
2159 }
2160}
2161
2162void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002163{
Mathias Agopian841cde52012-03-01 15:44:37 -08002164 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002165 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002166
David Sodmanfa9b2af2017-12-24 13:28:59 -08002167 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002168
David Sodmanfa9b2af2017-12-24 13:28:59 -08002169 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002170 const auto displayId = display->getId();
2171 if (displayId >= 0) {
2172 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002173 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002174 display->onSwapBuffersCompleted();
2175 display->makeCurrent();
David Sodman15094112018-10-11 09:39:37 -07002176 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002177 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002178
Chia-I Wu7b549592017-11-15 09:14:57 -08002179 // The layer buffer from the previous frame (if any) is released
2180 // by HWC only when the release fence from this frame (if any) is
2181 // signaled. Always get the release fence from HWC first.
David Sodman15094112018-10-11 09:39:37 -07002182 auto hwcLayer = layer->getHwcLayer(displayId);
2183 if (displayId >= 0) {
2184 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002185 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002186
2187 // If the layer was client composited in the previous frame, we
2188 // need to merge with the previous client target acquire fence.
2189 // Since we do not track that, always merge with the current
2190 // client target acquire fence when it is available, even though
2191 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002192 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002193 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002194 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002195 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002196
David Sodman15094112018-10-11 09:39:37 -07002197 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002198 }
Chia-I Wu83806892017-11-16 10:50:20 -08002199
2200 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002201 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002202 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002203 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002204 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002205 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002206 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002207 }
2208 }
2209
Dominik Laskowski7e045462018-05-30 13:02:02 -07002210 if (displayId >= 0) {
2211 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002212 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002213 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002214}
2215
Mathias Agopian87baae12012-07-31 12:38:26 -07002216void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002217{
Mathias Agopian841cde52012-03-01 15:44:37 -08002218 ATRACE_CALL();
2219
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002220 // here we keep a copy of the drawing state (that is the state that's
2221 // going to be overwritten by handleTransactionLocked()) outside of
2222 // mStateLock so that the side-effects of the State assignment
2223 // don't happen with mStateLock held (which can cause deadlocks).
2224 State drawingState(mDrawingState);
2225
Mathias Agopianca4d3602011-05-19 15:38:14 -07002226 Mutex::Autolock _l(mStateLock);
2227 const nsecs_t now = systemTime();
2228 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002229
Mathias Agopianca4d3602011-05-19 15:38:14 -07002230 // Here we're guaranteed that some transaction flags are set
2231 // so we can call handleTransactionLocked() unconditionally.
2232 // We call getTransactionFlags(), which will also clear the flags,
2233 // with mStateLock held to guarantee that mCurrentState won't change
2234 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002235
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002236 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002237 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002238 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002239
Mathias Agopianca4d3602011-05-19 15:38:14 -07002240 mLastTransactionTime = systemTime() - now;
2241 mDebugInTransaction = 0;
2242 invalidateHwcGeometry();
2243 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002244}
2245
Dominik Laskowski7e045462018-05-30 13:02:02 -07002246DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002247 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002248 // Figure out whether the event is for the primary display or an
2249 // external display by matching the Hwc display id against one for a
2250 // connected display. If we did not find a match, we then check what
2251 // displays are not already connected to determine the type. If we don't
2252 // have a connected primary display, we assume the new display is meant to
2253 // be the primary display, and then if we don't have an external display,
2254 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002255 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2256 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002257 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002258 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002259 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002260 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002261 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002262 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002263 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002264 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002265 return DisplayDevice::DISPLAY_EXTERNAL;
2266 }
2267
2268 return DisplayDevice::DISPLAY_ID_INVALID;
2269}
2270
Lloyd Piqueba04e622017-12-14 17:11:26 -08002271void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2272 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002273 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002274 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002275 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002276 continue;
2277 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002278
2279 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2280 ALOGE("External displays are not supported by the vr hardware composer.");
2281 continue;
2282 }
2283
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002284 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002285 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002286 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002287 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002288 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002289
2290 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002291 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002292 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002293 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002294 DisplayDeviceState info;
2295 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002296 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2297 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002298 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002299 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002300 mInterceptor->saveDisplayCreation(info);
2301 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002302 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002303 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002304
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002305 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002306 if (idx >= 0) {
2307 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002308 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002309 mCurrentState.displays.removeItemsAt(idx);
2310 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002311 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002312 }
2313
2314 processDisplayChangesLocked();
2315 }
2316
2317 mPendingHotplugEvents.clear();
2318}
2319
Lloyd Pique99d3da52018-01-22 17:48:03 -08002320sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002321 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002322 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002323 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2324 creationArgs.isSecure = state.isSecure;
2325 creationArgs.displaySurface = dispSurface;
2326 creationArgs.hasWideColorGamut = false;
2327 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002328
Peiyong Lin13effd12018-07-24 17:01:47 -07002329 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002330 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002331 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002332 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002333 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002334 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002335
Dominik Laskowski7e045462018-05-30 13:02:02 -07002336 std::vector<RenderIntent> renderIntents =
2337 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002338 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002339 }
tangrobin6753a022018-08-10 10:58:54 +08002340 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002341
tangrobin6753a022018-08-10 10:58:54 +08002342 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002343 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2344 creationArgs.supportedPerFrameMetadata =
2345 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002346 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002347
2348 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2349 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002350 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002351
2352 /*
2353 * Create our display's surface
2354 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002355 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002356 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002357 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002358 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002359 creationArgs.displayWidth = renderSurface->getWidth();
2360 creationArgs.displayHeight = renderSurface->getHeight();
2361 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002362
2363 // Make sure that composition can never be stalled by a virtual display
2364 // consumer that isn't processing buffers fast enough. We have to do this
2365 // in two places:
2366 // * Here, in case the display is composed entirely by HWC.
2367 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2368 // window's swap interval in eglMakeCurrent, so they'll override the
2369 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002370 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002371 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2372 }
2373
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002374 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2375 ? primaryDisplayOrientation
2376 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002377
Lloyd Pique99d3da52018-01-22 17:48:03 -08002378 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002379 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002380
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002381 sp<DisplayDevice> display = new DisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002382
2383 if (maxFrameBufferAcquiredBuffers >= 3) {
2384 nativeWindowSurface->preallocateBuffers();
2385 }
2386
2387 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002388 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002389 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002390 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002391 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002392 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002393 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002394 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002395 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002396 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002397 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002398 display->setLayerStack(state.layerStack);
2399 display->setProjection(state.orientation, state.viewport, state.frame);
2400 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002401
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002402 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002403}
2404
Lloyd Pique347200f2017-12-14 17:00:15 -08002405void SurfaceFlinger::processDisplayChangesLocked() {
2406 // here we take advantage of Vector's copy-on-write semantics to
2407 // improve performance by skipping the transaction entirely when
2408 // know that the lists are identical
2409 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2410 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2411 if (!curr.isIdenticalTo(draw)) {
2412 mVisibleRegionsDirty = true;
2413 const size_t cc = curr.size();
2414 size_t dc = draw.size();
2415
2416 // find the displays that were removed
2417 // (ie: in drawing state but not in current state)
2418 // also handle displays that changed
2419 // (ie: displays that are in both lists)
2420 for (size_t i = 0; i < dc;) {
2421 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2422 if (j < 0) {
2423 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002424 // Call makeCurrent() on the primary display so we can
2425 // be sure that nothing associated with this display
2426 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002427 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2428 defaultDisplay->makeCurrent();
2429 }
2430 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2431 display->disconnect(getHwComposer());
2432 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002433 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002434 if (mUseScheduler) {
2435 mScheduler->hotplugReceived(mAppConnectionHandle,
2436 EventThread::DisplayType::Primary, false);
2437 } else {
2438 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2439 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002440 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002441 if (mUseScheduler) {
2442 mScheduler->hotplugReceived(mAppConnectionHandle,
2443 EventThread::DisplayType::External, false);
2444 } else {
2445 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2446 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002447 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002448 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002449 } else {
2450 // this display is in both lists. see if something changed.
2451 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002452 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002453 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2454 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2455 if (state_binder != draw_binder) {
2456 // changing the surface is like destroying and
2457 // recreating the DisplayDevice, so we just remove it
2458 // from the drawing state, so that it get re-added
2459 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002460 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2461 display->disconnect(getHwComposer());
2462 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002463 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002464 mDrawingState.displays.removeItemsAt(i);
2465 dc--;
2466 // at this point we must loop to the next item
2467 continue;
2468 }
2469
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002470 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002471 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002472 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002473 }
2474 if ((state.orientation != draw[i].orientation) ||
2475 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002476 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002477 }
2478 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002479 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002480 }
2481 }
2482 }
2483 ++i;
2484 }
2485
2486 // find displays that were added
2487 // (ie: in current state but not in drawing state)
2488 for (size_t i = 0; i < cc; i++) {
2489 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2490 const DisplayDeviceState& state(curr[i]);
2491
2492 sp<DisplaySurface> dispSurface;
2493 sp<IGraphicBufferProducer> producer;
2494 sp<IGraphicBufferProducer> bqProducer;
2495 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002496 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002497
Dominik Laskowski7e045462018-05-30 13:02:02 -07002498 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002499 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002500 // Virtual displays without a surface are dormant:
2501 // they have external state (layer stack, projection,
2502 // etc.) but no internal state (i.e. a DisplayDevice).
2503 if (state.surface != nullptr) {
2504 // Allow VR composer to use virtual displays.
2505 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2506 int width = 0;
2507 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2508 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2509 int height = 0;
2510 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2511 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2512 int intFormat = 0;
2513 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2514 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002515 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002516
Dominik Laskowski7e045462018-05-30 13:02:02 -07002517 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2518 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002519 }
2520
2521 // TODO: Plumb requested format back up to consumer
2522
2523 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002524 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002525 bqProducer, bqConsumer,
2526 state.displayName);
2527
2528 dispSurface = vds;
2529 producer = vds;
2530 }
2531 } else {
2532 ALOGE_IF(state.surface != nullptr,
2533 "adding a supported display, but rendering "
2534 "surface is provided (%p), ignoring it",
2535 state.surface.get());
2536
Dominik Laskowski7e045462018-05-30 13:02:02 -07002537 displayId = state.type;
2538 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002539 producer = bqProducer;
2540 }
2541
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002542 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002543 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002544 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002545 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002546 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002547 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002548 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002549 if (mUseScheduler) {
2550 mScheduler->hotplugReceived(mAppConnectionHandle,
2551 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002552 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002553 } else {
2554 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2555 true);
2556 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002557 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002558 if (mUseScheduler) {
2559 mScheduler->hotplugReceived(mAppConnectionHandle,
2560 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002561 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002562 } else {
2563 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2564 true);
2565 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002566 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002567 }
2568 }
2569 }
2570 }
2571 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002572
2573 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002574}
2575
Mathias Agopian87baae12012-07-31 12:38:26 -07002576void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002577{
Dan Stoza7dde5992015-05-22 09:51:44 -07002578 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002579 mCurrentState.traverseInZOrder([](Layer* layer) {
2580 layer->notifyAvailableFrames();
2581 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002582
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583 /*
2584 * Traversal of the children
2585 * (perform the transaction for each of them if needed)
2586 */
2587
Mathias Agopian3559b072012-08-15 13:46:03 -07002588 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002589 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002591 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592
2593 const uint32_t flags = layer->doTransaction(0);
2594 if (flags & Layer::eVisibleRegion)
2595 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002596 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597 }
2598
2599 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002600 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601 */
2602
Mathias Agopiane57f2922012-08-09 16:29:12 -07002603 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002604 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002605 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002606 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002608 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002609 // The transform hint might have changed for some layers
2610 // (either because a display has changed, or because a layer
2611 // as changed).
2612 //
2613 // Walk through all the layers in currentLayers,
2614 // and update their transform hint.
2615 //
2616 // If a layer is visible only on a single display, then that
2617 // display is used to calculate the hint, otherwise we use the
2618 // default display.
2619 //
2620 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2621 // the hint is set before we acquire a buffer from the surface texture.
2622 //
2623 // NOTE: layer transactions have taken place already, so we use their
2624 // drawing state. However, SurfaceFlinger's own transaction has not
2625 // happened yet, so we must use the current state layer list
2626 // (soon to become the drawing state list).
2627 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002628 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002629 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002630 bool first = true;
2631 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002632 // NOTE: we rely on the fact that layers are sorted by
2633 // layerStack first (so we don't have to traverse the list
2634 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002635 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002636 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002637 currentlayerStack = layerStack;
2638 // figure out if this layerstack is mirrored
2639 // (more than one display) if so, pick the default display,
2640 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002641 hintDisplay = nullptr;
2642 for (const auto& [token, display] : mDisplays) {
2643 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2644 if (hintDisplay) {
2645 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002646 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002647 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002648 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002649 }
2650 }
2651 }
2652 }
Chet Haase91d25932013-04-11 15:24:55 -07002653
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002654 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002655 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2656 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002657
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002658 // could be null when this layer is using a layerStack
2659 // that is not visible on any display. Also can occur at
2660 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002661 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002662 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002663
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002664 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002665 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002666 if (hintDisplay) {
2667 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002668 }
Robert Carr2047fae2016-11-28 14:09:09 -08002669
2670 first = false;
2671 });
Mathias Agopian84300952012-11-21 16:02:13 -08002672 }
2673
2674
Mathias Agopian3559b072012-08-15 13:46:03 -07002675 /*
2676 * Perform our own transaction if needed
2677 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002678
2679 if (mLayersAdded) {
2680 mLayersAdded = false;
2681 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002682 mVisibleRegionsDirty = true;
2683 }
2684
2685 // some layers might have been removed, so
2686 // we need to update the regions they're exposing.
2687 if (mLayersRemoved) {
2688 mLayersRemoved = false;
2689 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002690 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002691 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002692 // this layer is not visible anymore
2693 // TODO: we could traverse the tree from front to back and
2694 // compute the actual visible region
2695 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002696 Region visibleReg;
2697 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002698 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002699 }
Robert Carr2047fae2016-11-28 14:09:09 -08002700 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002701 }
2702
2703 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002704
2705 updateCursorAsync();
2706}
2707
2708void SurfaceFlinger::updateCursorAsync()
2709{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002710 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002711 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002712 continue;
2713 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002714
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002715 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2716 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002717 }
2718 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002719}
2720
2721void SurfaceFlinger::commitTransaction()
2722{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002723 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002724 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002725 for (const auto& l : mLayersPendingRemoval) {
2726 recordBufferingStats(l->getName().string(),
2727 l->getOccupancyHistory(true));
Jorim Jaggi10c985e2018-10-23 11:17:45 +00002728 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002729 }
2730 mLayersPendingRemoval.clear();
2731 }
2732
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002733 // If this transaction is part of a window animation then the next frame
2734 // we composite should be considered an animation as well.
2735 mAnimCompositionPending = mAnimTransactionPending;
2736
Mathias Agopian4fec8732012-06-29 14:12:52 -07002737 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002738 // clear the "changed" flags in current state
2739 mCurrentState.colorMatrixChanged = false;
2740
Robert Carr1f0a16a2016-10-24 16:27:39 -07002741 mDrawingState.traverseInZOrder([](Layer* layer) {
2742 layer->commitChildList();
2743 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002744 mTransactionPending = false;
2745 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002746 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747}
2748
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002749void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2750 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002751 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002752 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002753
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002754 Region aboveOpaqueLayers;
2755 Region aboveCoveredLayers;
2756 Region dirty;
2757
Mathias Agopian87baae12012-07-31 12:38:26 -07002758 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759
Robert Carr2047fae2016-11-28 14:09:09 -08002760 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002762 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763
Jesse Hall01e29052013-02-19 16:13:35 -08002764 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002765 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002766 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002767 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002768
Mathias Agopianab028732010-03-16 16:41:46 -07002769 /*
2770 * opaqueRegion: area of a surface that is fully opaque.
2771 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002773
2774 /*
2775 * visibleRegion: area of a surface that is visible on screen
2776 * and not fully transparent. This is essentially the layer's
2777 * footprint minus the opaque regions above it.
2778 * Areas covered by a translucent surface are considered visible.
2779 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002781
2782 /*
2783 * coveredRegion: area of a surface that is covered by all
2784 * visible regions above it (which includes the translucent areas).
2785 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002787
Jesse Halla8026d22012-09-25 13:25:04 -07002788 /*
2789 * transparentRegion: area of a surface that is hinted to be completely
2790 * transparent. This is only used to tell when the layer has no visible
2791 * non-transparent regions and can be removed from the layer list. It
2792 * does not affect the visibleRegion of this layer or any layers
2793 * beneath it. The hint may not be correct if apps don't respect the
2794 * SurfaceView restrictions (which, sadly, some don't).
2795 */
2796 Region transparentRegion;
2797
Mathias Agopianab028732010-03-16 16:41:46 -07002798
2799 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002800 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002801 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002802 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002804 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002805 if (!visibleRegion.isEmpty()) {
2806 // Remove the transparent area from the visible region
2807 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002808 if (tr.preserveRects()) {
2809 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002810 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002811 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002812 // transformation too complex, can't do the
2813 // transparent region optimization.
2814 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002815 }
Mathias Agopianab028732010-03-16 16:41:46 -07002816 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817
Mathias Agopianab028732010-03-16 16:41:46 -07002818 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002819 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002820 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002821 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002822 // the opaque region is the layer's footprint
2823 opaqueRegion = visibleRegion;
2824 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825 }
2826 }
2827
Robert Carre5f4f692018-01-12 13:12:28 -08002828 if (visibleRegion.isEmpty()) {
2829 layer->clearVisibilityRegions();
2830 return;
2831 }
2832
Mathias Agopianab028732010-03-16 16:41:46 -07002833 // Clip the covered region to the visible region
2834 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2835
2836 // Update aboveCoveredLayers for next (lower) layer
2837 aboveCoveredLayers.orSelf(visibleRegion);
2838
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002839 // subtract the opaque region covered by the layers above us
2840 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841
2842 // compute this layer's dirty region
2843 if (layer->contentDirty) {
2844 // we need to invalidate the whole region
2845 dirty = visibleRegion;
2846 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002847 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848 layer->contentDirty = false;
2849 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002850 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002851 * the exposed region consists of two components:
2852 * 1) what's VISIBLE now and was COVERED before
2853 * 2) what's EXPOSED now less what was EXPOSED before
2854 *
2855 * note that (1) is conservative, we start with the whole
2856 * visible region but only keep what used to be covered by
2857 * something -- which mean it may have been exposed.
2858 *
2859 * (2) handles areas that were not covered by anything but got
2860 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002861 */
Mathias Agopianab028732010-03-16 16:41:46 -07002862 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002863 const Region oldVisibleRegion = layer->visibleRegion;
2864 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002865 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2866 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867 }
2868 dirty.subtractSelf(aboveOpaqueLayers);
2869
2870 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002871 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872
Mathias Agopianab028732010-03-16 16:41:46 -07002873 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002875
Jesse Halla8026d22012-09-25 13:25:04 -07002876 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877 layer->setVisibleRegion(visibleRegion);
2878 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002879 layer->setVisibleNonTransparentRegion(
2880 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002881 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882
Mathias Agopian87baae12012-07-31 12:38:26 -07002883 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884}
2885
Chia-I Wuab0c3192017-08-01 11:29:00 -07002886void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002887 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002888 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2889 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002890 }
2891 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002892}
2893
Dan Stoza6b9454d2014-11-07 16:00:59 -08002894bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002896 ALOGV("handlePageFlip");
2897
Brian Andersond6927fb2016-07-23 23:37:30 -07002898 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002899
Mathias Agopian4fec8732012-06-29 14:12:52 -07002900 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002901 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002902 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002903
2904 // Store the set of layers that need updates. This set must not change as
2905 // buffers are being latched, as this could result in a deadlock.
2906 // Example: Two producers share the same command stream and:
2907 // 1.) Layer 0 is latched
2908 // 2.) Layer 0 gets a new frame
2909 // 2.) Layer 1 gets a new frame
2910 // 3.) Layer 1 is latched.
2911 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2912 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002913 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002914 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002915 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002916 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2917 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002918 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002919 } else {
2920 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002921 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002922 } else {
2923 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002924 }
Robert Carr2047fae2016-11-28 14:09:09 -08002925 });
2926
Dan Stoza9e56aa02015-11-02 13:00:03 -08002927 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002928 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002929 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002930 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002931 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002932 newDataLatched = true;
2933 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002934 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002935
Alec Mouri86770e52018-09-24 22:40:58 +00002936 // Clear the renderengine fence here...
2937 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2938 // clear instead of sp::clear.
2939 getBE().flushFence = Fence::NO_FENCE;
2940
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002941 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002942
2943 // If we will need to wake up at some time in the future to deal with a
2944 // queued frame that shouldn't be displayed during this vsync period, wake
2945 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002946 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002947 signalLayerUpdate();
2948 }
2949
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002950 // enter boot animation on first buffer latch
2951 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2952 ALOGI("Enter boot animation");
2953 mBootStage = BootStage::BOOTANIMATION;
2954 }
2955
Dan Stoza6b9454d2014-11-07 16:00:59 -08002956 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002957 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958}
2959
Mathias Agopianad456f92011-01-13 17:53:01 -08002960void SurfaceFlinger::invalidateHwcGeometry()
2961{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002962 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002963}
2964
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002965void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2966 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002967 // We only need to actually compose the display if:
2968 // 1) It is being handled by hardware composer, which may need this to
2969 // keep its virtual display state machine in sync, or
2970 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002971 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002972 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002973 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002974 return;
2975 }
2976
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002978 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002979
2980 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002981 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982}
2983
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002984bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002985 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002986
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002987 const Region bounds(display->bounds());
2988 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002989 const auto displayId = display->getId();
2990 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002991 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002992
Peiyong Lind3788632018-09-18 16:01:31 -07002993 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002994 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002995 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002996
Dan Stoza9e56aa02015-11-02 13:00:03 -08002997 if (hasClientComposition) {
2998 ALOGV("hasClientComposition");
2999
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003000 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003001 if (display->hasWideColorGamut()) {
3002 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003003 }
3004 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003005 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003006 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003007
Dominik Laskowski7e045462018-05-30 13:02:02 -07003008 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003009 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3010 HWC2::Capability::SkipClientColorTransform);
3011
Peiyong Lind3788632018-09-18 16:01:31 -07003012 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003013 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3014 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003015 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003016 }
3017
Chia-I Wud49d6692018-06-27 07:17:41 +08003018 // The current enhanced saturation matrix is designed to enhance Display P3,
3019 // thus we only apply this matrix when the render intent is not colorimetric
3020 // and the output color space is Display P3.
3021 needsEnhancedColorMatrix =
3022 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3023 outputDataspace == Dataspace::DISPLAY_P3);
3024 if (needsEnhancedColorMatrix) {
3025 colorMatrix *= mEnhancedSaturationMatrix;
3026 }
3027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003028 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003029 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003030 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003031 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003032
3033 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003034 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3035 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3036 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003037 }
3038 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003039 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003040
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003041 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003042 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003043 // when using overlays, we assume a fully transparent framebuffer
3044 // NOTE: we could reduce how much we need to clear, for instance
3045 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003046 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003047 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003048 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003049 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003050 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003051 // we're left with the letterbox region
3052 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003053 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003054
3055 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003056 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003057
Mathias Agopianb9494d52012-04-18 02:28:45 -07003058 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003059 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003060 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003061 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003062 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003063 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003064
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003065 const Rect& bounds = display->getBounds();
3066 const Rect& scissor = display->getScissor();
3067 if (scissor != bounds) {
3068 // scissor doesn't match the screen's dimensions, so we
3069 // need to clear everything outside of it and enable
3070 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003071
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003072 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003073 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003074 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003075 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003076
Mathias Agopian85d751c2012-08-29 16:59:24 -07003077 /*
3078 * and then, render the layers targeted at the framebuffer
3079 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003080
Dan Stoza9e56aa02015-11-02 13:00:03 -08003081 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003082 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003083 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003084 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003085 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003086 displayTransform.transform(layer->visibleRegion)));
3087 ALOGV("Layer: %s", layer->getName().string());
3088 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003089 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003090 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003091 case HWC2::Composition::Cursor:
3092 case HWC2::Composition::Device:
3093 case HWC2::Composition::Sideband:
3094 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003095 const Layer::State& state(layer->getDrawingState());
3096 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3097 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3098 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003099 // never clear the very first layer since we're
3100 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003101 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003102 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003103 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003104 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003105 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003106 if (layer->hasColorTransform()) {
3107 mat4 tmpMatrix;
3108 if (applyColorMatrix) {
3109 tmpMatrix = mDrawingState.colorMatrix;
3110 }
3111 tmpMatrix *= layer->getColorTransform();
3112 if (needsEnhancedColorMatrix) {
3113 tmpMatrix *= mEnhancedSaturationMatrix;
3114 }
3115 getRenderEngine().setColorTransform(tmpMatrix);
3116 } else {
3117 getRenderEngine().setColorTransform(colorMatrix);
3118 }
David Sodmanc1498e62018-09-12 14:36:26 -07003119 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003120 break;
3121 }
3122 default:
3123 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003124 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003125 } else {
3126 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003127 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003128 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003129 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003130
Peiyong Lind3788632018-09-18 16:01:31 -07003131 // Clear color transform matrix at the end of the frame.
3132 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003133
Mathias Agopianf45c5102012-10-24 16:29:17 -07003134 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003135 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003136 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137}
3138
Chia-I Wu28e3a252018-09-07 12:05:02 -07003139void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003140 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003141 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142}
3143
Dan Stoza7d89d062015-04-30 13:29:25 -07003144status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003145 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003146 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003147 const sp<Layer>& lbc,
3148 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003149{
Dan Stoza7d89d062015-04-30 13:29:25 -07003150 // add this layer to the current state list
3151 {
3152 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003153 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003154 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3155 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003156 return NO_MEMORY;
3157 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003158 if (parent == nullptr) {
3159 mCurrentState.layersSortedByZ.add(lbc);
3160 } else {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003161 if (parent->isPendingRemoval()) {
3162 ALOGE("addClientLayer called with a removed parent");
3163 return NAME_NOT_FOUND;
3164 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003165 parent->addChild(lbc);
3166 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003167
Yiwei Zhang243b3782018-05-15 17:40:04 -07003168 if (gbc != nullptr) {
3169 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3170 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3171 mMaxGraphicBufferProducerListSize,
3172 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3173 mGraphicBufferProducerList.size(),
3174 mMaxGraphicBufferProducerListSize, mNumLayers);
3175 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003176 mLayersAdded = true;
3177 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003178 }
3179
Mathias Agopian96f08192010-06-02 23:28:45 -07003180 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003181 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003182
Dan Stoza7d89d062015-04-30 13:29:25 -07003183 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003184}
3185
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003186status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003187 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003188 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3189}
Robert Carr7f9b8992017-03-10 11:08:39 -08003190
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003191status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
chaviwca27f252018-02-06 16:46:39 -08003192 bool topLevelOnly) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003193 if (layer->isPendingRemoval()) {
3194 return NO_ERROR;
3195 }
3196
Robert Carr1f0a16a2016-10-24 16:27:39 -07003197 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003198 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003199 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003200 if (topLevelOnly) {
3201 return NO_ERROR;
3202 }
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003203
3204 sp<Layer> ancestor = p;
3205 while (ancestor->getParent() != nullptr) {
3206 ancestor = ancestor->getParent();
3207 }
3208 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3209 ALOGE("removeLayer called with a layer whose parent has been removed");
3210 return NAME_NOT_FOUND;
3211 }
3212
Chia-I Wufae51c42017-06-15 12:53:59 -07003213 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003214 } else {
3215 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003216 }
3217
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003218 // As a matter of normal operation, the LayerCleaner will produce a second
3219 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3220 // so we will succeed in promoting it, but it's already been removed
3221 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3222 // otherwise something has gone wrong and we are leaking the layer.
3223 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
3224 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3225 layer->getName().string(),
3226 (p != nullptr) ? p->getName().string() : "no-parent");
3227 return BAD_VALUE;
3228 } else if (index < 0) {
3229 return NO_ERROR;
3230 }
Robert Carrf478f9f2018-10-15 12:43:33 -07003231
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003232 layer->onRemovedFromCurrentState();
3233 mLayersPendingRemoval.add(layer);
3234 mLayersRemoved = true;
3235 mNumLayers -= 1 + layer->getChildrenCount();
3236 setTransactionFlags(eTransactionNeeded);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003237 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238}
3239
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003240uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003241 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003242}
3243
Mathias Agopian3f844832013-08-07 21:24:32 -07003244uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003245 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003246}
3247
Mathias Agopian3f844832013-08-07 21:24:32 -07003248uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003249 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003250}
3251
3252uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003253 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003254 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003255 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003256 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003257 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003258 }
3259 return old;
3260}
3261
chaviwca27f252018-02-06 16:46:39 -08003262bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3263 for (const ComposerState& state : states) {
3264 // Here we need to check that the interface we're given is indeed
3265 // one of our own. A malicious client could give us a nullptr
3266 // IInterface, or one of its own or even one of our own but a
3267 // different type. All these situations would cause us to crash.
3268 if (state.client == nullptr) {
3269 return true;
3270 }
3271
3272 sp<IBinder> binder = IInterface::asBinder(state.client);
3273 if (binder == nullptr) {
3274 return true;
3275 }
3276
3277 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3278 return true;
3279 }
3280 }
3281 return false;
3282}
3283
Mathias Agopian8b33f032012-07-24 20:43:54 -07003284void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003285 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003286 const Vector<DisplayState>& displays,
3287 uint32_t flags)
3288{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003289 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003290 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003291 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003292
chaviwca27f252018-02-06 16:46:39 -08003293 if (containsAnyInvalidClientState(states)) {
3294 return;
3295 }
3296
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003297 if (flags & eAnimation) {
3298 // For window updates that are part of an animation we must wait for
3299 // previous animation "frames" to be handled.
3300 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003301 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003302 if (CC_UNLIKELY(err != NO_ERROR)) {
3303 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003304 // caller after a few seconds.
3305 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3306 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003307 mAnimTransactionPending = false;
3308 break;
3309 }
3310 }
3311 }
3312
chaviwca27f252018-02-06 16:46:39 -08003313 for (const DisplayState& display : displays) {
3314 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003315 }
3316
chaviwca27f252018-02-06 16:46:39 -08003317 for (const ComposerState& state : states) {
3318 transactionFlags |= setClientStateLocked(state);
3319 }
3320
3321 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3322 // as destroyed should only occur after setting all other states. This is to allow for a
3323 // child re-parent to happen before marking its original parent as destroyed (which would
3324 // then mark the child as destroyed).
3325 for (const ComposerState& state : states) {
3326 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003327 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003328
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003329 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3330 // anyway. This can be used as a flush mechanism for previous async transactions.
3331 // Empty animation transaction can be used to simulate back-pressure, so also force a
3332 // transaction for empty animation transactions.
3333 if (transactionFlags == 0 &&
3334 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003335 transactionFlags = eTransactionNeeded;
3336 }
3337
Mathias Agopian386aa982011-11-07 21:58:03 -08003338 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003339 if (mInterceptor->isEnabled()) {
3340 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003341 }
Irvel468051e2016-06-13 16:44:44 -07003342
Mathias Agopian386aa982011-11-07 21:58:03 -08003343 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003344 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3345 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003346 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003347
3348 // if this is a synchronous transaction, wait for it to take effect
3349 // before returning.
3350 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003351 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003352 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003353 if (flags & eAnimation) {
3354 mAnimTransactionPending = true;
3355 }
3356 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003357 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3358 if (CC_UNLIKELY(err != NO_ERROR)) {
3359 // just in case something goes wrong in SF, return to the
3360 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003361 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3362 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003363 break;
3364 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003365 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003366 }
3367}
3368
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003369uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3370 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3371 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003372
Mathias Agopiane57f2922012-08-09 16:29:12 -07003373 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003374 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3375
3376 const uint32_t what = s.what;
3377 if (what & DisplayState::eSurfaceChanged) {
3378 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3379 state.surface = s.surface;
3380 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003381 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003382 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003383 if (what & DisplayState::eLayerStackChanged) {
3384 if (state.layerStack != s.layerStack) {
3385 state.layerStack = s.layerStack;
3386 flags |= eDisplayTransactionNeeded;
3387 }
3388 }
3389 if (what & DisplayState::eDisplayProjectionChanged) {
3390 if (state.orientation != s.orientation) {
3391 state.orientation = s.orientation;
3392 flags |= eDisplayTransactionNeeded;
3393 }
3394 if (state.frame != s.frame) {
3395 state.frame = s.frame;
3396 flags |= eDisplayTransactionNeeded;
3397 }
3398 if (state.viewport != s.viewport) {
3399 state.viewport = s.viewport;
3400 flags |= eDisplayTransactionNeeded;
3401 }
3402 }
3403 if (what & DisplayState::eDisplaySizeChanged) {
3404 if (state.width != s.width) {
3405 state.width = s.width;
3406 flags |= eDisplayTransactionNeeded;
3407 }
3408 if (state.height != s.height) {
3409 state.height = s.height;
3410 flags |= eDisplayTransactionNeeded;
3411 }
3412 }
3413
Mathias Agopiane57f2922012-08-09 16:29:12 -07003414 return flags;
3415}
3416
Robert Carrd4ae7f32018-06-07 16:10:57 -07003417bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3418 IPCThreadState* ipc = IPCThreadState::self();
3419 const int pid = ipc->getCallingPid();
3420 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003421 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003422 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003423 return false;
3424 }
3425 return true;
3426}
3427
chaviwca27f252018-02-06 16:46:39 -08003428uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3429 const layer_state_t& s = composerState.state;
3430 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3431
Mathias Agopian13127d82013-03-05 17:47:11 -08003432 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003433 if (layer == nullptr) {
3434 return 0;
3435 }
3436
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003437 if (layer->isPendingRemoval()) {
3438 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3439 return 0;
3440 }
3441
chaviw8b3871a2017-11-01 17:41:01 -07003442 uint32_t flags = 0;
3443
3444 const uint32_t what = s.what;
3445 bool geometryAppliesWithResize =
3446 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003447
3448 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3449 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003450 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003451 layer->pushPendingState();
3452 }
3453
chaviw8b3871a2017-11-01 17:41:01 -07003454 if (what & layer_state_t::ePositionChanged) {
3455 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3456 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003457 }
chaviw8b3871a2017-11-01 17:41:01 -07003458 }
3459 if (what & layer_state_t::eLayerChanged) {
3460 // NOTE: index needs to be calculated before we update the state
3461 const auto& p = layer->getParent();
3462 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003463 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003464 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003465 mCurrentState.layersSortedByZ.removeAt(idx);
3466 mCurrentState.layersSortedByZ.add(layer);
3467 // we need traversal (state changed)
3468 // AND transaction (list changed)
3469 flags |= eTransactionNeeded|eTraversalNeeded;
3470 }
chaviw8b3871a2017-11-01 17:41:01 -07003471 } else {
3472 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003473 flags |= eTransactionNeeded|eTraversalNeeded;
3474 }
3475 }
chaviw8b3871a2017-11-01 17:41:01 -07003476 }
3477 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003478 // NOTE: index needs to be calculated before we update the state
3479 const auto& p = layer->getParent();
3480 if (p == nullptr) {
3481 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3482 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3483 mCurrentState.layersSortedByZ.removeAt(idx);
3484 mCurrentState.layersSortedByZ.add(layer);
3485 // we need traversal (state changed)
3486 // AND transaction (list changed)
3487 flags |= eTransactionNeeded|eTraversalNeeded;
3488 }
3489 } else {
3490 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3491 flags |= eTransactionNeeded|eTraversalNeeded;
3492 }
chaviw8b3871a2017-11-01 17:41:01 -07003493 }
3494 }
3495 if (what & layer_state_t::eSizeChanged) {
3496 if (layer->setSize(s.w, s.h)) {
3497 flags |= eTraversalNeeded;
3498 }
3499 }
3500 if (what & layer_state_t::eAlphaChanged) {
3501 if (layer->setAlpha(s.alpha))
3502 flags |= eTraversalNeeded;
3503 }
3504 if (what & layer_state_t::eColorChanged) {
3505 if (layer->setColor(s.color))
3506 flags |= eTraversalNeeded;
3507 }
Peiyong Lind3788632018-09-18 16:01:31 -07003508 if (what & layer_state_t::eColorTransformChanged) {
3509 if (layer->setColorTransform(s.colorTransform)) {
3510 flags |= eTraversalNeeded;
3511 }
3512 }
chaviw8b3871a2017-11-01 17:41:01 -07003513 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003514 // TODO: b/109894387
3515 //
3516 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3517 // rotation. To see the problem observe that if we have a square parent, and a child
3518 // of the same size, then we rotate the child 45 degrees around it's center, the child
3519 // must now be cropped to a non rectangular 8 sided region.
3520 //
3521 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3522 // private API, and the WindowManager only uses rotation in one case, which is on a top
3523 // level layer in which cropping is not an issue.
3524 //
3525 // However given that abuse of rotation matrices could lead to surfaces extending outside
3526 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3527 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3528 // transformations.
3529 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003530 flags |= eTraversalNeeded;
3531 }
3532 if (what & layer_state_t::eTransparentRegionChanged) {
3533 if (layer->setTransparentRegionHint(s.transparentRegion))
3534 flags |= eTraversalNeeded;
3535 }
3536 if (what & layer_state_t::eFlagsChanged) {
3537 if (layer->setFlags(s.flags, s.mask))
3538 flags |= eTraversalNeeded;
3539 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003540 if (what & layer_state_t::eCropChanged_legacy) {
3541 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003542 flags |= eTraversalNeeded;
3543 }
chaviw8b3871a2017-11-01 17:41:01 -07003544 if (what & layer_state_t::eLayerStackChanged) {
3545 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3546 // We only allow setting layer stacks for top level layers,
3547 // everything else inherits layer stack from its parent.
3548 if (layer->hasParent()) {
3549 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3550 layer->getName().string());
3551 } else if (idx < 0) {
3552 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3553 "that also does not appear in the top level layer list. Something"
3554 " has gone wrong.", layer->getName().string());
3555 } else if (layer->setLayerStack(s.layerStack)) {
3556 mCurrentState.layersSortedByZ.removeAt(idx);
3557 mCurrentState.layersSortedByZ.add(layer);
3558 // we need traversal (state changed)
3559 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003560 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003561 }
3562 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003563 if (what & layer_state_t::eDeferTransaction_legacy) {
3564 if (s.barrierHandle_legacy != nullptr) {
3565 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3566 } else if (s.barrierGbp_legacy != nullptr) {
3567 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003568 if (authenticateSurfaceTextureLocked(gbp)) {
3569 const auto& otherLayer =
3570 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003571 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003572 } else {
3573 ALOGE("Attempt to defer transaction to to an"
3574 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003575 }
3576 }
chaviw8b3871a2017-11-01 17:41:01 -07003577 // We don't trigger a traversal here because if no other state is
3578 // changed, we don't want this to cause any more work
3579 }
3580 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003581 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003582 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003583 if (!hadParent) {
3584 mCurrentState.layersSortedByZ.remove(layer);
3585 }
chaviw8b3871a2017-11-01 17:41:01 -07003586 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003587 }
chaviw8b3871a2017-11-01 17:41:01 -07003588 }
3589 if (what & layer_state_t::eReparentChildren) {
3590 if (layer->reparentChildren(s.reparentHandle)) {
3591 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003592 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003593 }
chaviw8b3871a2017-11-01 17:41:01 -07003594 if (what & layer_state_t::eDetachChildren) {
3595 layer->detachChildren();
3596 }
3597 if (what & layer_state_t::eOverrideScalingModeChanged) {
3598 layer->setOverrideScalingMode(s.overrideScalingMode);
3599 // We don't trigger a traversal here because if no other state is
3600 // changed, we don't want this to cause any more work
3601 }
Marissa Wall61c58622018-07-18 10:12:20 -07003602 if (what & layer_state_t::eTransformChanged) {
3603 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3604 }
3605 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3606 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3607 flags |= eTraversalNeeded;
3608 }
3609 if (what & layer_state_t::eCropChanged) {
3610 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3611 }
3612 if (what & layer_state_t::eBufferChanged) {
3613 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3614 }
3615 if (what & layer_state_t::eAcquireFenceChanged) {
3616 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3617 }
3618 if (what & layer_state_t::eDataspaceChanged) {
3619 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3620 }
3621 if (what & layer_state_t::eHdrMetadataChanged) {
3622 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3623 }
3624 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3625 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3626 }
3627 if (what & layer_state_t::eApiChanged) {
3628 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3629 }
3630 if (what & layer_state_t::eSidebandStreamChanged) {
3631 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3632 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003633 return flags;
3634}
3635
chaviwca27f252018-02-06 16:46:39 -08003636void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3637 const layer_state_t& state = composerState.state;
3638 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3639
3640 sp<Layer> layer(client->getLayerUser(state.surface));
3641 if (layer == nullptr) {
3642 return;
3643 }
3644
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003645 if (layer->isPendingRemoval()) {
3646 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3647 return;
3648 }
3649
chaviwca27f252018-02-06 16:46:39 -08003650 if (state.what & layer_state_t::eDestroySurface) {
3651 removeLayerLocked(mStateLock, layer);
3652 }
3653}
3654
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003655status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003656 const String8& name,
3657 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003658 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003659 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003660 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003661{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003662 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003663 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003664 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003665 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003666 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003667
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003668 status_t result = NO_ERROR;
3669
3670 sp<Layer> layer;
3671
Cody Northropbc755282017-03-31 12:00:08 -06003672 String8 uniqueName = getUniqueLayerName(name);
3673
Mathias Agopian3165cc22012-08-08 19:42:09 -07003674 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003675 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003676 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3677 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003678
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003679 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003680 case ISurfaceComposerClient::eFXSurfaceBufferState:
3681 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3682 break;
chaviw13fdc492017-06-27 12:40:18 -07003683 case ISurfaceComposerClient::eFXSurfaceColor:
3684 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003685 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003686 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003687 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003688 case ISurfaceComposerClient::eFXSurfaceContainer:
3689 result = createContainerLayer(client,
3690 uniqueName, w, h, flags,
3691 handle, &layer);
3692 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003693 default:
3694 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003695 break;
3696 }
3697
Dan Stoza7d89d062015-04-30 13:29:25 -07003698 if (result != NO_ERROR) {
3699 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003700 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003701
Chia-I Wuab0c3192017-08-01 11:29:00 -07003702 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3703 // TODO b/64227542
3704 if (windowType == 441731) {
3705 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3706 layer->setPrimaryDisplayOnly();
3707 }
3708
Albert Chaulk479c60c2017-01-27 14:21:34 -05003709 layer->setInfo(windowType, ownerUid);
3710
Robert Carr1f0a16a2016-10-24 16:27:39 -07003711 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003712 if (result != NO_ERROR) {
3713 return result;
3714 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003715 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003716
3717 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003718 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003719}
3720
Cody Northropbc755282017-03-31 12:00:08 -06003721String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3722{
3723 bool matchFound = true;
3724 uint32_t dupeCounter = 0;
3725
3726 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3727 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3728
Dan Stoza436ccf32018-06-21 12:10:12 -07003729 // Grab the state lock since we're accessing mCurrentState
3730 Mutex::Autolock lock(mStateLock);
3731
Cody Northropbc755282017-03-31 12:00:08 -06003732 // Loop over layers until we're sure there is no matching name
3733 while (matchFound) {
3734 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003735 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003736 if (layer->getName() == uniqueName) {
3737 matchFound = true;
3738 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3739 }
3740 });
3741 }
3742
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003743 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3744 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003745
3746 return uniqueName;
3747}
3748
Marissa Wallfd668622018-05-10 10:21:13 -07003749status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3750 uint32_t w, uint32_t h, uint32_t flags,
3751 PixelFormat& format, sp<IBinder>* handle,
3752 sp<IGraphicBufferProducer>* gbp,
3753 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003754 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003755 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003756 case PIXEL_FORMAT_TRANSPARENT:
3757 case PIXEL_FORMAT_TRANSLUCENT:
3758 format = PIXEL_FORMAT_RGBA_8888;
3759 break;
3760 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003761 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003762 break;
3763 }
3764
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003765 sp<BufferQueueLayer> layer =
3766 new BufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003767 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003768 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003769 *handle = layer->getHandle();
3770 *gbp = layer->getProducer();
3771 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003772 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003773
Marissa Wallfd668622018-05-10 10:21:13 -07003774 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003775 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003776}
3777
Marissa Wall61c58622018-07-18 10:12:20 -07003778status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3779 uint32_t w, uint32_t h, uint32_t flags,
3780 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003781 sp<BufferStateLayer> layer =
3782 new BufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003783 *handle = layer->getHandle();
3784 *outLayer = layer;
3785
3786 return NO_ERROR;
3787}
3788
chaviw13fdc492017-06-27 12:40:18 -07003789status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003790 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003791 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003792{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003793 *outLayer = new ColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003794 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003795 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003796}
3797
Robert Carr6b3f6c52018-08-13 13:05:17 -07003798status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3799 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3800 sp<IBinder>* handle, sp<Layer>* outLayer)
3801{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003802 *outLayer = new ContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003803 *handle = (*outLayer)->getHandle();
3804 return NO_ERROR;
3805}
3806
3807
Mathias Agopianac9fa422013-02-11 16:40:36 -08003808status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003809{
Robert Carr9524cb32017-02-13 11:32:32 -08003810 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003811 status_t err = NO_ERROR;
3812 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003813 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003814 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003815 err = removeLayer(l);
3816 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3817 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003818 }
3819 return err;
3820}
3821
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003822status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003823{
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003824 // called by ~LayerCleaner() when all references to the IBinder (handle)
3825 // are gone
3826 sp<Layer> l = layer.promote();
3827 if (l == nullptr) {
3828 // The layer has already been removed, carry on
3829 return NO_ERROR;
3830 }
3831 // If we have a parent, then we can continue to live as long as it does.
3832 return removeLayer(l, true);
Rob Carr4bba3702018-10-08 21:53:30 +00003833}
3834
Mathias Agopianb60314a2012-04-10 22:09:54 -07003835// ---------------------------------------------------------------------------
3836
Andy McFadden13a082e2012-08-24 10:16:42 -07003837void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003838 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3839 if (!displayToken) return;
3840
Jesse Hall01e29052013-02-19 16:13:35 -08003841 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003842 Vector<ComposerState> state;
3843 Vector<DisplayState> displays;
3844 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003845 d.what = DisplayState::eDisplayProjectionChanged |
3846 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003847 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003848 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003849 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003850 d.frame.makeInvalid();
3851 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003852 d.width = 0;
3853 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003854 displays.add(d);
3855 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003856
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003857 const auto display = getDisplayDevice(displayToken);
3858 if (!display) return;
3859
3860 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3861
3862 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003863 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003864 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003865
Brian Andersond0010582017-03-07 13:20:31 -08003866 // Use phase of 0 since phase is not known.
3867 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003868 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3869 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003870}
3871
3872void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003873 // Async since we may be called from the main thread.
3874 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003875}
3876
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003877void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3878 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003879 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003880 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003881
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003882 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003883 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003884 return;
3885 }
3886
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003887 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003888 ALOGW("Trying to set power mode for virtual display");
3889 return;
3890 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003891
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003892 display->setPowerMode(mode);
3893
Lloyd Pique4dccc412018-01-22 17:21:36 -08003894 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003895 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003896 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003897 if (idx < 0) {
3898 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3899 return;
3900 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003901 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003902 }
3903
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003904 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003905 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003906 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003907 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003908 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003909 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003910 if (mUseScheduler) {
3911 mScheduler->onScreenAcquired(mAppConnectionHandle);
3912 } else {
3913 mEventThread->onScreenAcquired();
3914 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003915 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003916 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003917
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003918 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003919 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003920 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003921
3922 struct sched_param param = {0};
3923 param.sched_priority = 1;
3924 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3925 ALOGW("Couldn't set SCHED_FIFO on display on");
3926 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003927 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003928 // Turn off the display
3929 struct sched_param param = {0};
3930 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3931 ALOGW("Couldn't set SCHED_OTHER on display off");
3932 }
3933
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003934 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003935 if (mUseScheduler) {
3936 mScheduler->disableHardwareVsync(true);
3937 } else {
3938 disableHardwareVsync(true); // also cancels any in-progress resync
3939 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003940 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003941 if (mUseScheduler) {
3942 mScheduler->onScreenReleased(mAppConnectionHandle);
3943 } else {
3944 mEventThread->onScreenReleased();
3945 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003946 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003947
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003948 getHwComposer().setPowerMode(type, mode);
3949 mVisibleRegionsDirty = true;
3950 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003951 } else if (mode == HWC_POWER_MODE_DOZE ||
3952 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003953 // Update display while dozing
3954 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003955 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003956 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003957 if (mUseScheduler) {
3958 mScheduler->onScreenAcquired(mAppConnectionHandle);
3959 } else {
3960 mEventThread->onScreenAcquired();
3961 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003962 resyncToHardwareVsync(true);
3963 }
3964 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3965 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003966 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003967 if (mUseScheduler) {
3968 mScheduler->disableHardwareVsync(true);
3969 } else {
3970 disableHardwareVsync(true); // also cancels any in-progress resync
3971 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003972 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003973 if (mUseScheduler) {
3974 mScheduler->onScreenReleased(mAppConnectionHandle);
3975 } else {
3976 mEventThread->onScreenReleased();
3977 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003978 }
3979 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003980 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003981 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003982 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003983 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003984
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003985 if (display->isPrimary()) {
3986 mTimeStats.setPowerMode(mode);
3987 }
3988
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003989 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003990}
3991
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003992void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003993 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003994 const auto display = getDisplayDevice(displayToken);
3995 if (!display) {
3996 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3997 displayToken.get());
3998 } else if (display->isVirtual()) {
3999 ALOGW("Attempt to set power mode %d for virtual display", mode);
4000 } else {
4001 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004002 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004003 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004004}
4005
4006// ---------------------------------------------------------------------------
4007
Lloyd Pique755e3192018-01-31 16:46:15 -08004008status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4009 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004010 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004011
Mathias Agopianbd115332013-04-18 16:41:04 -07004012 IPCThreadState* ipc = IPCThreadState::self();
4013 const int pid = ipc->getCallingPid();
4014 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004015
Mathias Agopianbd115332013-04-18 16:41:04 -07004016 if ((uid != AID_SHELL) &&
4017 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004018 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004019 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004020 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004021 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004022 // (this would indicate SF is stuck, but we want to be able to
4023 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004024 status_t err = mStateLock.timedLock(s2ns(1));
4025 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004026 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004027 result.appendFormat(
4028 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4029 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004030 }
4031
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004032 bool dumpAll = true;
4033 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004034 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004035
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004036 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004037 if ((index < numArgs) &&
4038 (args[index] == String16("--list"))) {
4039 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004040 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004041 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004042 }
4043
4044 if ((index < numArgs) &&
4045 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004046 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004047 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004048 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004049 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004050
4051 if ((index < numArgs) &&
4052 (args[index] == String16("--latency-clear"))) {
4053 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004054 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004055 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004056 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004057
4058 if ((index < numArgs) &&
4059 (args[index] == String16("--dispsync"))) {
4060 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004061 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004062 dumpAll = false;
4063 }
Dan Stozab90cf072015-03-05 11:05:59 -08004064
4065 if ((index < numArgs) &&
4066 (args[index] == String16("--static-screen"))) {
4067 index++;
4068 dumpStaticScreenStats(result);
4069 dumpAll = false;
4070 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004071
4072 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004073 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004074 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004075 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004076 dumpAll = false;
4077 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004078
4079 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4080 index++;
4081 dumpWideColorInfo(result);
4082 dumpAll = false;
4083 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004084
4085 if ((index < numArgs) &&
4086 (args[index] == String16("--enable-layer-stats"))) {
4087 index++;
4088 mLayerStats.enable();
4089 dumpAll = false;
4090 }
4091
4092 if ((index < numArgs) &&
4093 (args[index] == String16("--disable-layer-stats"))) {
4094 index++;
4095 mLayerStats.disable();
4096 dumpAll = false;
4097 }
4098
4099 if ((index < numArgs) &&
4100 (args[index] == String16("--clear-layer-stats"))) {
4101 index++;
4102 mLayerStats.clear();
4103 dumpAll = false;
4104 }
4105
4106 if ((index < numArgs) &&
4107 (args[index] == String16("--dump-layer-stats"))) {
4108 index++;
4109 mLayerStats.dump(result);
4110 dumpAll = false;
4111 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004112
4113 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004114 (args[index] == String16("--frame-composition"))) {
4115 index++;
4116 dumpFrameCompositionInfo(result);
4117 dumpAll = false;
4118 }
4119
4120 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004121 (args[index] == String16("--display-identification"))) {
4122 index++;
4123 dumpDisplayIdentificationData(result);
4124 dumpAll = false;
4125 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004126
4127 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4128 index++;
4129 mTimeStats.parseArgs(asProto, args, index, result);
4130 dumpAll = false;
4131 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004132 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004133
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004134 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004135 if (asProto) {
4136 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4137 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4138 } else {
4139 dumpAllLocked(args, index, result);
4140 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004141 }
4142
Mathias Agopian9795c422009-08-26 16:36:26 -07004143 if (locked) {
4144 mStateLock.unlock();
4145 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004146 }
4147 write(fd, result.string(), result.size());
4148 return NO_ERROR;
4149}
4150
Dan Stozac7014012014-02-14 15:03:43 -08004151void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4152 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004153{
Robert Carr2047fae2016-11-28 14:09:09 -08004154 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004155 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004156 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004157}
4158
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004159void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004160 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004161{
4162 String8 name;
4163 if (index < args.size()) {
4164 name = String8(args[index]);
4165 index++;
4166 }
4167
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004168 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4169 getHwComposer().isConnected(displayId)) {
4170 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4171 const nsecs_t period = activeConfig->getVsyncPeriod();
4172 result.appendFormat("%" PRId64 "\n", period);
4173 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004174
4175 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004176 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004177 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004178 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004179 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004180 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004181 }
Robert Carr2047fae2016-11-28 14:09:09 -08004182 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004183 }
4184}
4185
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004186void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004187 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004188{
4189 String8 name;
4190 if (index < args.size()) {
4191 name = String8(args[index]);
4192 index++;
4193 }
4194
Robert Carr2047fae2016-11-28 14:09:09 -08004195 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004196 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004197 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004198 }
Robert Carr2047fae2016-11-28 14:09:09 -08004199 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004200
Svetoslavd85084b2014-03-20 10:28:31 -07004201 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004202}
4203
Jamie Gennis6547ff42013-07-16 20:12:42 -07004204// This should only be called from the main thread. Otherwise it would need
4205// the lock and should use mCurrentState rather than mDrawingState.
4206void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004207 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004208 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004209 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004210
4211 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4212}
4213
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004214void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004215{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004216 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004217
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004218 if (isLayerTripleBufferingDisabled())
4219 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004220
4221 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004222 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004223 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004224 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004225 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4226 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004227 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004228}
4229
Dan Stozab90cf072015-03-05 11:05:59 -08004230void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4231{
4232 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004233 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4234 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004235 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004236 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004237 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4238 b + 1, bucketTimeSec, percent);
4239 }
David Sodman4a36e932017-11-07 14:29:47 -08004240 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004241 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004242 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004243 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004244 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004245}
4246
Dan Stozae77c7662016-05-13 11:37:28 -07004247void SurfaceFlinger::recordBufferingStats(const char* layerName,
4248 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004249 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4250 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004251 for (const auto& segment : history) {
4252 if (!segment.usedThirdBuffer) {
4253 stats.twoBufferTime += segment.totalTime;
4254 }
4255 if (segment.occupancyAverage < 1.0f) {
4256 stats.doubleBufferedTime += segment.totalTime;
4257 } else if (segment.occupancyAverage < 2.0f) {
4258 stats.tripleBufferedTime += segment.totalTime;
4259 }
4260 ++stats.numSegments;
4261 stats.totalTime += segment.totalTime;
4262 }
4263}
4264
Brian Andersond6927fb2016-07-23 23:37:30 -07004265void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4266 result.appendFormat("Layer frame timestamps:\n");
4267
4268 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4269 const size_t count = currentLayers.size();
4270 for (size_t i=0 ; i<count ; i++) {
4271 currentLayers[i]->dumpFrameEvents(result);
4272 }
4273}
4274
Dan Stozae77c7662016-05-13 11:37:28 -07004275void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4276 result.append("Buffering stats:\n");
4277 result.append(" [Layer name] <Active time> <Two buffer> "
4278 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004279 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004280 typedef std::tuple<std::string, float, float, float> BufferTuple;
4281 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004282 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004283 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004284 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004285 if (stats.numSegments == 0) {
4286 continue;
4287 }
4288 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4289 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4290 stats.totalTime;
4291 float doubleBufferRatio = static_cast<float>(
4292 stats.doubleBufferedTime) / stats.totalTime;
4293 float tripleBufferRatio = static_cast<float>(
4294 stats.tripleBufferedTime) / stats.totalTime;
4295 sorted.insert({activeTime, {name, twoBufferRatio,
4296 doubleBufferRatio, tripleBufferRatio}});
4297 }
4298 for (const auto& sortedPair : sorted) {
4299 float activeTime = sortedPair.first;
4300 const BufferTuple& values = sortedPair.second;
4301 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4302 std::get<0>(values).c_str(), activeTime,
4303 std::get<1>(values), std::get<2>(values),
4304 std::get<3>(values));
4305 }
4306 result.append("\n");
4307}
4308
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004309void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004310 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004311 const int32_t displayId = display->getId();
4312 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4313 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004314 continue;
4315 }
4316
Dominik Laskowski7e045462018-05-30 13:02:02 -07004317 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004318 uint8_t port;
4319 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004320 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004321 result.append("no identification data\n");
4322 continue;
4323 }
4324
4325 if (!isEdid(data)) {
4326 result.append("unknown identification data: ");
4327 for (uint8_t byte : data) {
4328 result.appendFormat("%x ", byte);
4329 }
4330 result.append("\n");
4331 continue;
4332 }
4333
4334 const auto edid = parseEdid(data);
4335 if (!edid) {
4336 result.append("invalid EDID: ");
4337 for (uint8_t byte : data) {
4338 result.appendFormat("%x ", byte);
4339 }
4340 result.append("\n");
4341 continue;
4342 }
4343
4344 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4345 result.append(edid->displayName.data(), edid->displayName.length());
4346 result.append("\"\n");
4347 }
4348 result.append("\n");
4349}
4350
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004351void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004352 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4353 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004354 result.appendFormat("DisplayColorSetting: %s\n",
4355 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004356
4357 // TODO: print out if wide-color mode is active or not
4358
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004359 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004360 const int32_t displayId = display->getId();
4361 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004362 continue;
4363 }
4364
Dominik Laskowski7e045462018-05-30 13:02:02 -07004365 result.appendFormat("Display %d color modes:\n", displayId);
4366 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004367 for (auto&& mode : modes) {
4368 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4369 }
4370
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004371 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004372 result.appendFormat(" Current color mode: %s (%d)\n",
4373 decodeColorMode(currentMode).c_str(), currentMode);
4374 }
4375 result.append("\n");
4376}
4377
David Sodman7e4ae112018-02-09 15:02:28 -08004378void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4379 std::string stringResult;
4380
4381 for (const auto& [token, display] : mDisplays) {
4382 const auto displayId = display->getId();
4383 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4384 continue;
4385 }
4386
4387 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4388 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4389 break;
4390 }
4391 const auto& compositionInfoList = compositionInfoIt->second;
4392 stringResult += base::StringPrintf("Display: %d\n", displayId);
4393 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4394 for (const auto& compositionInfo : compositionInfoList) {
4395 compositionInfo.dump(stringResult, nullptr);
4396 stringResult += base::StringPrintf("\n");
4397 }
4398 }
4399
4400 result.append(stringResult.c_str());
4401}
4402
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004403LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004404 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004405 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4406 const State& state = useDrawing ? mDrawingState : mCurrentState;
4407 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004408 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004409 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004410 });
4411
4412 return layersProto;
4413}
4414
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004415LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004416 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004417
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004418 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004419 resolution->set_w(display.getWidth());
4420 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004421
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004422 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4423 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4424 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004425
Dominik Laskowski7e045462018-05-30 13:02:02 -07004426 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004427 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004428 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004429 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004430 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004431 }
4432 });
4433
4434 return layersProto;
4435}
4436
Mathias Agopian74d211a2013-04-22 16:55:35 +02004437void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4438 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004439{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004440 bool colorize = false;
4441 if (index < args.size()
4442 && (args[index] == String16("--color"))) {
4443 colorize = true;
4444 index++;
4445 }
4446
4447 Colorizer colorizer(colorize);
4448
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004449 // figure out if we're stuck somewhere
4450 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004451 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004452 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4453
4454 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004455 * Dump library configuration.
4456 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004457
4458 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004459 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004460 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004461 appendSfConfigString(result);
4462 appendUiConfigString(result);
4463 appendGuiConfigString(result);
4464 result.append("\n");
4465
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004466 result.append("\nDisplay identification data:\n");
4467 dumpDisplayIdentificationData(result);
4468
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004469 result.append("\nWide-Color information:\n");
4470 dumpWideColorInfo(result);
4471
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004472 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004473 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004474 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004475 result.append(SyncFeatures::getInstance().toString());
4476 result.append("\n");
4477
Andy McFadden41d67d72014-04-25 16:58:34 -07004478 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004479 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004480 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004481
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004482 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4483 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004484 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4485 getHwComposer().isConnected(displayId)) {
4486 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004487 result.appendFormat("Display %d: "
4488 "app phase %" PRId64 " ns, "
4489 "sf phase %" PRId64 " ns, "
4490 "early app phase %" PRId64 " ns, "
4491 "early sf phase %" PRId64 " ns, "
4492 "early app gl phase %" PRId64 " ns, "
4493 "early sf gl phase %" PRId64 " ns, "
4494 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4495 displayId,
4496 vsyncPhaseOffsetNs,
4497 sfVsyncPhaseOffsetNs,
4498 appEarlyOffset,
4499 sfEarlyOffset,
4500 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004501 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004502 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004503 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004504 result.append("\n");
4505
Dan Stozab90cf072015-03-05 11:05:59 -08004506 // Dump static screen stats
4507 result.append("\n");
4508 dumpStaticScreenStats(result);
4509 result.append("\n");
4510
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004511 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4512
Dan Stozae77c7662016-05-13 11:37:28 -07004513 dumpBufferingStats(result);
4514
Andy McFadden4803b742012-09-24 19:07:20 -07004515 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004516 * Dump the visible layer list
4517 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004518 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004519 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004520 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4521 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004522 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004523
Chia-I Wu2f884132018-09-13 15:17:58 -07004524 {
4525 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4526 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4527 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4528 result.append("\n");
4529 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004530
David Sodman7e4ae112018-02-09 15:02:28 -08004531 result.append("\nFrame-Composition information:\n");
4532 dumpFrameCompositionInfo(result);
4533 result.append("\n");
4534
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004535 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004536 * Dump Display state
4537 */
4538
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004539 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004540 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004541 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004542 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004543 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004544 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004545 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004546
4547 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004548 * Dump SurfaceFlinger global state
4549 */
4550
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004551 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004552 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004553 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004554
Mathias Agopian888c8222012-08-04 21:10:38 -07004555 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004556 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004557
David Sodmanbc815282017-11-05 18:57:52 -08004558 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004559
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004560 if (display) {
4561 display->undefinedRegion.dump(result, "undefinedRegion");
4562 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4563 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004564 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004565 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004566 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004567 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004568
4569 if (display) {
4570 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4571 result.appendFormat(" refresh-rate : %f fps\n"
4572 " x-dpi : %f\n"
4573 " y-dpi : %f\n",
4574 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4575 activeConfig->getDpiY());
4576 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004577
Mathias Agopian74d211a2013-04-22 16:55:35 +02004578 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004579 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004580
Ana Krulec98b5b242018-08-10 15:03:23 -07004581 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004582 /*
4583 * VSYNC state
4584 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004585 if (mUseScheduler) {
4586 mScheduler->dump(mAppConnectionHandle, result);
4587 } else {
4588 mEventThread->dump(result);
4589 }
Dan Stozae22aec72016-08-01 13:20:59 -07004590 result.append("\n");
4591
4592 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004593 * Tracing state
4594 */
4595 mTracing.dump(result);
4596 result.append("\n");
4597
4598 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004599 * HWC layer minidump
4600 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004601 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004602 const int32_t displayId = display->getId();
4603 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004604 continue;
4605 }
4606
Dominik Laskowski7e045462018-05-30 13:02:02 -07004607 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004608 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004609 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004610 result.append("\n");
4611 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004612
4613 /*
4614 * Dump HWComposer state
4615 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004616 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004617 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004618 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004619 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004620 result.appendFormat(" h/w composer %s\n",
4621 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004622 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004623
4624 /*
4625 * Dump gralloc state
4626 */
4627 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4628 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004629
4630 /*
4631 * Dump VrFlinger state if in use.
4632 */
4633 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4634 result.append("VrFlinger state:\n");
4635 result.append(mVrFlinger->Dump().c_str());
4636 result.append("\n");
4637 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004638}
4639
Dominik Laskowski7e045462018-05-30 13:02:02 -07004640const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004641 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004642 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004643 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004644 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004645 }
4646 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004647
4648 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4649 static const Vector<sp<Layer>> empty;
4650 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004651}
4652
Keun young Park63f165f2012-08-31 10:53:36 -07004653bool SurfaceFlinger::startDdmConnection()
4654{
4655 void* libddmconnection_dso =
4656 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4657 if (!libddmconnection_dso) {
4658 return false;
4659 }
4660 void (*DdmConnection_start)(const char* name);
4661 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004662 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004663 if (!DdmConnection_start) {
4664 dlclose(libddmconnection_dso);
4665 return false;
4666 }
4667 (*DdmConnection_start)(getServiceName());
4668 return true;
4669}
4670
Chia-I Wu28f320b2018-05-03 11:02:56 -07004671void SurfaceFlinger::updateColorMatrixLocked() {
4672 mat4 colorMatrix;
4673 if (mGlobalSaturationFactor != 1.0f) {
4674 // Rec.709 luma coefficients
4675 float3 luminance{0.213f, 0.715f, 0.072f};
4676 luminance *= 1.0f - mGlobalSaturationFactor;
4677 mat4 saturationMatrix = mat4(
4678 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4679 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4680 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4681 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4682 );
4683 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4684 } else {
4685 colorMatrix = mClientColorMatrix * mDaltonizer();
4686 }
4687
4688 if (mCurrentState.colorMatrix != colorMatrix) {
4689 mCurrentState.colorMatrix = colorMatrix;
4690 mCurrentState.colorMatrixChanged = true;
4691 setTransactionFlags(eTransactionNeeded);
4692 }
4693}
4694
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004695status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004696#pragma clang diagnostic push
4697#pragma clang diagnostic error "-Wswitch-enum"
4698 switch (static_cast<ISurfaceComposerTag>(code)) {
4699 // These methods should at minimum make sure that the client requested
4700 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004701 case BOOT_FINISHED:
4702 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004703 case CREATE_CONNECTION:
4704 case CREATE_DISPLAY:
4705 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004706 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004707 case GET_ACTIVE_COLOR_MODE:
4708 case GET_ANIMATION_FRAME_STATS:
4709 case GET_HDR_CAPABILITIES:
4710 case SET_ACTIVE_CONFIG:
4711 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004712 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004713 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004714 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4715 IPCThreadState* ipc = IPCThreadState::self();
4716 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4717 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004718 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004719 }
Robert Carr1db73f62016-12-21 12:58:51 -08004720 return OK;
4721 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004722 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004723 IPCThreadState* ipc = IPCThreadState::self();
4724 const int pid = ipc->getCallingPid();
4725 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004726 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4727 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004728 return PERMISSION_DENIED;
4729 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004730 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004731 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004732 // Used by apps to hook Choreographer to SurfaceFlinger.
4733 case CREATE_DISPLAY_EVENT_CONNECTION:
4734 // The following calls are currently used by clients that do not
4735 // request necessary permissions. However, they do not expose any secret
4736 // information, so it is OK to pass them.
4737 case AUTHENTICATE_SURFACE:
4738 case GET_ACTIVE_CONFIG:
4739 case GET_BUILT_IN_DISPLAY:
4740 case GET_DISPLAY_COLOR_MODES:
4741 case GET_DISPLAY_CONFIGS:
4742 case GET_DISPLAY_STATS:
4743 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4744 // Calling setTransactionState is safe, because you need to have been
4745 // granted a reference to Client* and Handle* to do anything with it.
4746 case SET_TRANSACTION_STATE:
4747 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004748 case CREATE_SCOPED_CONNECTION:
4749 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004750 return OK;
4751 }
4752 case CAPTURE_LAYERS:
4753 case CAPTURE_SCREEN: {
4754 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004755 IPCThreadState* ipc = IPCThreadState::self();
4756 const int pid = ipc->getCallingPid();
4757 const int uid = ipc->getCallingUid();
4758 if ((uid != AID_GRAPHICS) &&
4759 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4760 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4761 return PERMISSION_DENIED;
4762 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004763 return OK;
4764 }
4765 // The following codes are deprecated and should never be allowed to access SF.
4766 case CONNECT_DISPLAY_UNUSED:
4767 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4768 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4769 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004770 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004771 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004772
4773 // These codes are used for the IBinder protocol to either interrogate the recipient
4774 // side of the transaction for its canonical interface descriptor or to dump its state.
4775 // We let them pass by default.
4776 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4777 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4778 code == IBinder::SYSPROPS_TRANSACTION) {
4779 return OK;
4780 }
4781 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4782 // in onTransact verifies that the user is root, and has access to use SF.
4783 if (code >= 1000 && code <= 1029) {
4784 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4785 return OK;
4786 }
4787 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4788 return PERMISSION_DENIED;
4789#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004790}
4791
Ana Krulec13be8ad2018-08-21 02:43:56 +00004792status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4793 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004794 status_t credentialCheck = CheckTransactCodeCredentials(code);
4795 if (credentialCheck != OK) {
4796 return credentialCheck;
4797 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004798
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004799 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4800 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004801 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004802 IPCThreadState* ipc = IPCThreadState::self();
4803 const int uid = ipc->getCallingUid();
4804 if (CC_UNLIKELY(uid != AID_SYSTEM
4805 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004806 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004807 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004808 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004809 return PERMISSION_DENIED;
4810 }
4811 int n;
4812 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004813 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004814 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004815 return NO_ERROR;
4816 case 1002: // SHOW_UPDATES
4817 n = data.readInt32();
4818 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004819 invalidateHwcGeometry();
4820 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004821 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004822 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004823 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004824 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004825 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004826 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004827 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004828 setTransactionFlags(
4829 eTransactionNeeded|
4830 eDisplayTransactionNeeded|
4831 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004832 return NO_ERROR;
4833 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004834 case 1006:{ // send empty update
4835 signalRefresh();
4836 return NO_ERROR;
4837 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004838 case 1008: // toggle use of hw composer
4839 n = data.readInt32();
4840 mDebugDisableHWC = n ? 1 : 0;
4841 invalidateHwcGeometry();
4842 repaintEverything();
4843 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004844 case 1009: // toggle use of transform hint
4845 n = data.readInt32();
4846 mDebugDisableTransformHint = n ? 1 : 0;
4847 invalidateHwcGeometry();
4848 repaintEverything();
4849 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004850 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004851 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004852 reply->writeInt32(0);
4853 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004854 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004855 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004856 return NO_ERROR;
4857 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004858 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004859 if (!display) {
4860 return NAME_NOT_FOUND;
4861 }
4862
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004863 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004864 return NO_ERROR;
4865 }
4866 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004867 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004868 // daltonize
4869 n = data.readInt32();
4870 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004871 case 1:
4872 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4873 break;
4874 case 2:
4875 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4876 break;
4877 case 3:
4878 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4879 break;
4880 default:
4881 mDaltonizer.setType(ColorBlindnessType::None);
4882 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004883 }
4884 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004885 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004886 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004887 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004888 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004889
4890 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004891 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004892 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004893 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004894 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004895 // apply a color matrix
4896 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004897 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004898 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004899 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004900 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004901 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004902 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004903 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004904 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004905 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004906 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004907
4908 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4909 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004910 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004911 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4912 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4913 }
4914
Chia-I Wu28f320b2018-05-03 11:02:56 -07004915 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004916 return NO_ERROR;
4917 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004918 // This is an experimental interface
4919 // Needs to be shifted to proper binder interface when we productize
4920 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004921 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004922 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004923 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004924 return NO_ERROR;
4925 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004926 case 1017: {
4927 n = data.readInt32();
4928 mForceFullDamage = static_cast<bool>(n);
4929 return NO_ERROR;
4930 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004931 case 1018: { // Modify Choreographer's phase offset
4932 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004933 if (mUseScheduler) {
4934 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4935 } else {
4936 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4937 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004938 return NO_ERROR;
4939 }
4940 case 1019: { // Modify SurfaceFlinger's phase offset
4941 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004942 if (mUseScheduler) {
4943 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4944 } else {
4945 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4946 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004947 return NO_ERROR;
4948 }
Irvel468051e2016-06-13 16:44:44 -07004949 case 1020: { // Layer updates interceptor
4950 n = data.readInt32();
4951 if (n) {
4952 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004953 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004954 }
4955 else{
4956 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004957 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004958 }
4959 return NO_ERROR;
4960 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004961 case 1021: { // Disable HWC virtual displays
4962 n = data.readInt32();
4963 mUseHwcVirtualDisplays = !n;
4964 return NO_ERROR;
4965 }
Romain Guy0147a172017-06-01 13:53:56 -07004966 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004967 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004968 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004969
Chia-I Wu28f320b2018-05-03 11:02:56 -07004970 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004971 return NO_ERROR;
4972 }
Romain Guy54f154a2017-10-24 21:40:32 +01004973 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004974 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004975 invalidateHwcGeometry();
4976 repaintEverything();
4977 return NO_ERROR;
4978 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004979 // Deprecate, use 1030 to check whether the device is color managed.
4980 case 1024: {
4981 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004982 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004983 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004984 n = data.readInt32();
4985 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004986 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004987 mTracing.enable();
4988 doTracing("tracing.enable");
4989 reply->writeInt32(NO_ERROR);
4990 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004991 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004992 status_t err = mTracing.disable();
4993 reply->writeInt32(err);
4994 }
4995 return NO_ERROR;
4996 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004997 case 1026: { // Get layer tracing status
4998 reply->writeBool(mTracing.isEnabled());
4999 return NO_ERROR;
5000 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005001 // Is a DisplayColorSetting supported?
5002 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005003 const auto display = getDefaultDisplayDevice();
5004 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005005 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005006 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005007
5008 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5009 switch (setting) {
5010 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005011 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005012 break;
5013 case DisplayColorSetting::UNMANAGED:
5014 reply->writeBool(true);
5015 break;
5016 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005017 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005018 break;
5019 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005020 reply->writeBool(
5021 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005022 break;
5023 }
5024 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005025 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005026 // Is VrFlinger active?
5027 case 1028: {
5028 Mutex::Autolock _l(mStateLock);
5029 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5030 return NO_ERROR;
5031 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005032 case 1029: {
5033 // Code 1029 is an experimental feature that allows applications to
5034 // simulate a high frequency panel by setting a multiplier and divisor
5035 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005036 // 0, then the code simply return the current multiplier and divisor.
5037 HWC2::Device::FrequencyScaler frequencyScaler;
5038 frequencyScaler.multiplier = data.readInt32();
5039 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005040
David Sodman44b5de02018-08-21 16:28:53 -07005041 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5042 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5043 reply->writeInt32(frequencyScaler.multiplier);
5044 reply->writeInt32(frequencyScaler.divisor);
5045 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005046 }
5047
David Sodman44b5de02018-08-21 16:28:53 -07005048 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
Ana Krulece588e312018-09-18 12:32:24 -07005049 if (mUseScheduler) {
5050 mScheduler->enableHardwareVsync();
5051 } else {
5052 enableHardwareVsync();
5053 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005054 } else {
Ana Krulece588e312018-09-18 12:32:24 -07005055 if (mUseScheduler) {
5056 mScheduler->disableHardwareVsync(true);
5057 } else {
5058 disableHardwareVsync(true);
5059 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005060 }
David Sodman44b5de02018-08-21 16:28:53 -07005061 mPrimaryDispSync->scalePeriod(frequencyScaler);
5062 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005063
David Sodman44b5de02018-08-21 16:28:53 -07005064 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5065 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5066
5067 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5068 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5069
5070 onHotplugReceived(getBE().mComposerSequenceId,
5071 hwcDisplayId, HWC2::Connection::Disconnected);
5072 onHotplugReceived(getBE().mComposerSequenceId,
5073 hwcDisplayId, HWC2::Connection::Connected);
5074 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5075 reply->writeInt32(frequencyScaler.multiplier);
5076 reply->writeInt32(frequencyScaler.divisor);
5077
David Sodman6d46c1e2018-07-13 12:59:48 -07005078 return NO_ERROR;
5079 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005080 // Is device color managed?
5081 case 1030: {
5082 reply->writeBool(useColorManagement);
5083 return NO_ERROR;
5084 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005085 }
5086 }
5087 return err;
5088}
5089
Steven Thomas6d8110b2017-08-31 18:24:21 -07005090void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005091 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005092 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005093}
5094
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005095// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5096class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005097public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005098 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5099 ~WindowDisconnector() {
5100 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005101 }
5102
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005103private:
5104 ANativeWindow* mWindow;
5105 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005106};
5107
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005108status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5109 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005110 uint32_t reqWidth, uint32_t reqHeight,
5111 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005112 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005113 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005114
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005115 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005116
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005117 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5118
Chia-I Wu20261cb2018-08-23 12:55:44 -07005119 sp<DisplayDevice> display;
5120 {
5121 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005122
Chia-I Wu20261cb2018-08-23 12:55:44 -07005123 display = getDisplayDeviceLocked(displayToken);
5124 if (!display) return BAD_VALUE;
5125
Chia-I Wu8730ba82018-08-29 09:25:59 -07005126 // ignore sourceCrop (i.e., use the projected logical display
5127 // viewport) until the framework is fixed
5128 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005129
5130 // set the requested width/height to the logical display viewport size
5131 // by default
5132 if (reqWidth == 0 || reqHeight == 0) {
5133 reqWidth = uint32_t(display->getViewport().width());
5134 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005135 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005136 }
5137
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005138 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005139
5140 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005141 display, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005142 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005143}
5144
5145status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005146 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005147 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005148 ATRACE_CALL();
5149
5150 class LayerRenderArea : public RenderArea {
5151 public:
Robert Carr578038f2018-03-09 12:25:24 -08005152 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5153 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005154 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005155 mLayer(layer),
5156 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005157 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005158 mFlinger(flinger),
5159 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005160 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005161 Rect getBounds() const override {
5162 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005163 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005164 }
Marissa Wall61c58622018-07-18 10:12:20 -07005165 int getHeight() const override {
5166 return mLayer->getActiveHeight(mLayer->getDrawingState());
5167 }
5168 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005169 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005170 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005171 Rect getSourceCrop() const override {
5172 if (mCrop.isEmpty()) {
5173 return getBounds();
5174 } else {
5175 return mCrop;
5176 }
5177 }
Robert Carr578038f2018-03-09 12:25:24 -08005178 class ReparentForDrawing {
5179 public:
5180 const sp<Layer>& oldParent;
5181 const sp<Layer>& newParent;
5182
5183 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5184 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005185 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005186 }
Robert Carr15eae092018-03-23 13:43:53 -07005187 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005188 };
5189
5190 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005191 const Rect sourceCrop = getSourceCrop();
5192 // no need to check rotation because there is none
5193 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5194 sourceCrop.height() != getReqHeight();
5195
Robert Carr578038f2018-03-09 12:25:24 -08005196 if (!mChildrenOnly) {
5197 mTransform = mLayer->getTransform().inverse();
5198 drawLayers();
5199 } else {
5200 Rect bounds = getBounds();
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005201 screenshotParentLayer = new ContainerLayer(
5202 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5203 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005204
5205 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5206 drawLayers();
5207 }
5208 }
chaviwa76b2712017-09-20 12:02:26 -07005209
chaviwa76b2712017-09-20 12:02:26 -07005210 private:
chaviw7206d492017-11-10 16:16:12 -08005211 const sp<Layer> mLayer;
5212 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005213
5214 // In the "childrenOnly" case we reparent the children to a screenshot
5215 // layer which has no properties set and which does not draw.
5216 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005217 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005218 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005219
5220 SurfaceFlinger* mFlinger;
5221 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005222 };
5223
5224 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5225 auto parent = layerHandle->owner.promote();
5226
Jorim Jaggi10c985e2018-10-23 11:17:45 +00005227 if (parent == nullptr || parent->isPendingRemoval()) {
chaviw7206d492017-11-10 16:16:12 -08005228 ALOGE("captureLayers called with a removed parent");
5229 return NAME_NOT_FOUND;
5230 }
5231
Robert Carr578038f2018-03-09 12:25:24 -08005232 const int uid = IPCThreadState::self()->getCallingUid();
5233 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5234 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5235 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5236 return PERMISSION_DENIED;
5237 }
5238
chaviw7206d492017-11-10 16:16:12 -08005239 Rect crop(sourceCrop);
5240 if (sourceCrop.width() <= 0) {
5241 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005242 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005243 }
5244
5245 if (sourceCrop.height() <= 0) {
5246 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005247 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005248 }
5249
5250 int32_t reqWidth = crop.width() * frameScale;
5251 int32_t reqHeight = crop.height() * frameScale;
5252
Chia-I Wu20261cb2018-08-23 12:55:44 -07005253 // really small crop or frameScale
5254 if (reqWidth <= 0) {
5255 reqWidth = 1;
5256 }
5257 if (reqHeight <= 0) {
5258 reqHeight = 1;
5259 }
5260
Robert Carr578038f2018-03-09 12:25:24 -08005261 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005262
Robert Carr578038f2018-03-09 12:25:24 -08005263 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005264 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5265 if (!layer->isVisible()) {
5266 return;
Robert Carr578038f2018-03-09 12:25:24 -08005267 } else if (childrenOnly && layer == parent.get()) {
5268 return;
chaviwa76b2712017-09-20 12:02:26 -07005269 }
5270 visitor(layer);
5271 });
5272 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005273 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005274}
5275
5276status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5277 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005278 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005279 bool useIdentityTransform) {
5280 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005281
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005282 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5283 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5284 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5285 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005286
5287 // This mutex protects syncFd and captureResult for communication of the return values from the
5288 // main thread back to this Binder thread
5289 std::mutex captureMutex;
5290 std::condition_variable captureCondition;
5291 std::unique_lock<std::mutex> captureLock(captureMutex);
5292 int syncFd = -1;
5293 std::optional<status_t> captureResult;
5294
Robert Carr03480e22018-01-04 16:02:06 -08005295 const int uid = IPCThreadState::self()->getCallingUid();
5296 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5297
Dominik Laskowski8c001672018-05-30 16:52:06 -07005298 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005299 // If there is a refresh pending, bug out early and tell the binder thread to try again
5300 // after the refresh.
5301 if (mRefreshPending) {
5302 ATRACE_NAME("Skipping screenshot for now");
5303 std::unique_lock<std::mutex> captureLock(captureMutex);
5304 captureResult = std::make_optional<status_t>(EAGAIN);
5305 captureCondition.notify_one();
5306 return;
5307 }
5308
5309 status_t result = NO_ERROR;
5310 int fd = -1;
5311 {
5312 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005313 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005314 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5315 useIdentityTransform, forSystem, &fd);
5316 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005317 }
5318
5319 {
5320 std::unique_lock<std::mutex> captureLock(captureMutex);
5321 syncFd = fd;
5322 captureResult = std::make_optional<status_t>(result);
5323 captureCondition.notify_one();
5324 }
5325 });
5326
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005327 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005328 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005329 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005330 while (*captureResult == EAGAIN) {
5331 captureResult.reset();
5332 result = postMessageAsync(message);
5333 if (result != NO_ERROR) {
5334 return result;
5335 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005336 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005337 }
5338 result = *captureResult;
5339 }
5340
5341 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005342 sync_wait(syncFd, -1);
5343 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005344 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005345
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005346 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005347}
5348
chaviwa76b2712017-09-20 12:02:26 -07005349void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005350 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005351 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005352 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005353
Lloyd Pique144e1162017-12-20 16:44:52 -08005354 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005355
chaviwa76b2712017-09-20 12:02:26 -07005356 const auto reqWidth = renderArea.getReqWidth();
5357 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005358 const auto sourceCrop = renderArea.getSourceCrop();
5359 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005360
Chia-I Wu36574d92018-05-16 10:54:36 -07005361 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5362 engine.setOutputDataSpace(Dataspace::SRGB);
5363 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005364
Mathias Agopian180f10d2013-04-10 22:55:41 -07005365 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005366 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005367
5368 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005369 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005370 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005371
chaviw50da5042018-04-09 13:49:37 -07005372 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005373 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005374 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005375
chaviwa76b2712017-09-20 12:02:26 -07005376 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005377 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005378 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005379 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005380 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005381}
5382
chaviwa76b2712017-09-20 12:02:26 -07005383status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5384 TraverseLayersFunction traverseLayers,
5385 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005386 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005387 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005388 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005389 ATRACE_CALL();
5390
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005391 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005392
5393 traverseLayers([&](Layer* layer) {
5394 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5395 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005396
Robert Carr03480e22018-01-04 16:02:06 -08005397 // We allow the system server to take screenshots of secure layers for
5398 // use in situations like the Screen-rotation animation and place
5399 // the impetus on WindowManager to not persist them.
5400 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005401 ALOGW("FB is protected: PERMISSION_DENIED");
5402 return PERMISSION_DENIED;
5403 }
5404
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005405 // this binds the given EGLImage as a framebuffer for the
5406 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005407 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005408 if (bufferBond.getStatus() != NO_ERROR) {
5409 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005410 return INVALID_OPERATION;
5411 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005412
Dan Stozaabcda352017-06-01 14:37:39 -07005413 // this will in fact render into our dequeued buffer
5414 // via an FBO, which means we didn't have to create
5415 // an EGLSurface and therefore we're not
5416 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005417 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005418
Alec Mouri492bc572018-09-11 21:40:04 +00005419 base::unique_fd syncFd = getRenderEngine().flush();
5420 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005421 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005422 }
Alec Mouri492bc572018-09-11 21:40:04 +00005423 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005424
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005425 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005426}
5427
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005428// ---------------------------------------------------------------------------
5429
Dan Stoza412903f2017-04-27 13:42:17 -07005430void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5431 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005432}
5433
Dan Stoza412903f2017-04-27 13:42:17 -07005434void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5435 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005436}
5437
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005438void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005439 const LayerVector::Visitor& visitor) {
5440 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005441 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005442 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005443 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005444 continue;
5445 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005446 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005447 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005448 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005449 return;
5450 }
chaviwa76b2712017-09-20 12:02:26 -07005451 if (!layer->isVisible()) {
5452 return;
5453 }
5454 visitor(layer);
5455 });
5456 }
5457}
5458
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005459}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005460
Lloyd Pique074e8122018-07-26 12:57:23 -07005461
Mathias Agopian3f844832013-08-07 21:24:32 -07005462#if defined(__gl_h_)
5463#error "don't include gl/gl.h in this file"
5464#endif
5465
5466#if defined(__gl2_h_)
5467#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005468#endif