blob: a1a8e22e8b9303ae0f272dad8bae0bb8cfb81133 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070077#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070078#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070080#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Steven Thomasb02664d2017-07-26 18:48:28 -070082#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070083#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070084#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070085#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070086#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070089#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070090#include "Scheduler/EventControlThread.h"
91#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070092#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070093#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070094#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070095
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070097
David Sodman7e4ae112018-02-09 15:02:28 -080098#include "android-base/stringprintf.h"
99
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900100#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800101#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700102#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800103#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900104#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105
chaviw1d044282017-09-27 12:19:28 -0700106#include <layerproto/LayerProtoParser.h>
107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108#define DISPLAY_COUNT 1
109
110namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700111
Jaesoo Lee43518572017-01-23 19:03:16 +0900112using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700114using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700115using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700116using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700117using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118
Steven Thomasb02664d2017-07-26 18:48:28 -0700119namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700120
121#pragma clang diagnostic push
122#pragma clang diagnostic error "-Wswitch-enum"
123
124bool isWideColorMode(const ColorMode colorMode) {
125 switch (colorMode) {
126 case ColorMode::DISPLAY_P3:
127 case ColorMode::ADOBE_RGB:
128 case ColorMode::DCI_P3:
129 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700130 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700131 case ColorMode::BT2100_PQ:
132 case ColorMode::BT2100_HLG:
133 return true;
134 case ColorMode::NATIVE:
135 case ColorMode::STANDARD_BT601_625:
136 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
137 case ColorMode::STANDARD_BT601_525:
138 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
139 case ColorMode::STANDARD_BT709:
140 case ColorMode::SRGB:
141 return false;
142 }
143 return false;
144}
145
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700146ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
147 switch (rotation) {
148 case ISurfaceComposer::eRotateNone:
149 return ui::Transform::ROT_0;
150 case ISurfaceComposer::eRotate90:
151 return ui::Transform::ROT_90;
152 case ISurfaceComposer::eRotate180:
153 return ui::Transform::ROT_180;
154 case ISurfaceComposer::eRotate270:
155 return ui::Transform::ROT_270;
156 }
157 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
158 return ui::Transform::ROT_0;
159}
160
Peiyong Linfca547f2018-07-09 13:03:33 -0700161#pragma clang diagnostic pop
162
Steven Thomasb02664d2017-07-26 18:48:28 -0700163class ConditionalLock {
164public:
165 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
166 if (lock) {
167 mMutex.lock();
168 }
169 }
170 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
171private:
172 Mutex& mMutex;
173 bool mLocked;
174};
Peiyong Linfca547f2018-07-09 13:03:33 -0700175
Peiyong Lin9d846a52018-11-05 13:18:20 -0800176// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
177bool validateCompositionDataspace(Dataspace dataspace) {
178 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
179}
180
Steven Thomasb02664d2017-07-26 18:48:28 -0700181} // namespace anonymous
182
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800183// ---------------------------------------------------------------------------
184
Mathias Agopian99b49842011-06-27 16:05:52 -0700185const String16 sHardwareTest("android.permission.HARDWARE_TEST");
186const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
187const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
188const String16 sDump("android.permission.DUMP");
189
190// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800191int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
192int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700193int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700194bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800195uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800196bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800197bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800198int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600199bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700200int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700201bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700202bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700203Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
204ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
205Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
206ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700207
Kalle Raitaa099a242017-01-11 11:17:29 -0800208std::string getHwcServiceName() {
209 char value[PROPERTY_VALUE_MAX] = {};
210 property_get("debug.sf.hwc_service_name", value, "default");
211 ALOGI("Using HWComposer service: '%s'", value);
212 return std::string(value);
213}
214
215bool useTrebleTestingOverride() {
216 char value[PROPERTY_VALUE_MAX] = {};
217 property_get("debug.sf.treble_testing_override", value, "false");
218 ALOGI("Treble testing override: '%s'", value);
219 return std::string(value) == "true";
220}
221
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800222std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
223 switch(displayColorSetting) {
224 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700225 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800226 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700227 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800228 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700229 return std::string("Enhanced");
230 default:
231 return std::string("Unknown ") +
232 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800233 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800234}
235
David Sodmanbc815282017-11-05 18:57:52 -0800236SurfaceFlingerBE::SurfaceFlingerBE()
237 : mHwcServiceName(getHwcServiceName()),
238 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800239 mFrameBuckets(),
240 mTotalTime(0),
241 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800242 mComposerSequenceId(0) {
243}
244
Lloyd Pique90c115d2018-09-18 21:39:42 -0700245SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
246 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800247 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700248 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700249 mTransactionPending(false),
250 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700251 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700252 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700254 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800255 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800256 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800257 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800258 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800259 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700260 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700261 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700262 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700263 mDebugInTransaction(0),
264 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700265 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700266 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700267 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800268 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800269 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800270 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700271 mVrFlingerRequestsDisplay(false),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700272 mMainThreadId(std::this_thread::get_id()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800273
Lloyd Pique90c115d2018-09-18 21:39:42 -0700274SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
275 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800276 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800277
278 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
280
281 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
283
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800284 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700287 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
289
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700290 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
292
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800293 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
295
Steven Thomas050b2c82017-03-06 11:45:16 -0800296 // Vr flinger is only enabled on Daydream ready devices.
297 useVrFlinger = getBool< ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::useVrFlinger>(false);
299
Fabien Sanglard1971b632017-03-10 14:50:03 -0800300 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
302
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600303 hasWideColorDisplay =
304 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700305 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700306 getBool<V1_2::ISurfaceFlingerConfigs,
307 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
308
309 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
310 if (surfaceFlingerConfigsServiceV1_2) {
311 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700312 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
313 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
314 defaultCompositionDataspace = tmpDefaultDataspace;
315 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
316 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
317 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
318 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700319 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800320 mDefaultCompositionDataspace = defaultCompositionDataspace;
321 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600322
Peiyong Linb3839ad2018-09-05 15:37:19 -0700323 useContextPriority = getBool<ISurfaceFlingerConfigs,
324 &ISurfaceFlingerConfigs::useContextPriority>(true);
325
Iris Chang7501ed62018-04-30 14:45:42 +0800326 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700327 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
328 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800329 V1_1::DisplayOrientation::ORIENTATION_0);
330
331 switch (primaryDisplayOrientation) {
332 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700333 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
335 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800340 break;
341 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
344 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800346
Lloyd Pique90c115d2018-09-18 21:39:42 -0700347 mPrimaryDispSync =
348 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
349 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351 // debugging stuff...
352 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700353
Mathias Agopianb4b17302013-03-20 18:36:41 -0700354 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700355 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700356
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800357 property_get("debug.sf.showupdates", value, "0");
358 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700359
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700360 property_get("debug.sf.ddms", value, "0");
361 mDebugDDMS = atoi(value);
362 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700363 if (!startDdmConnection()) {
364 // start failed, and DDMS debugging not enabled
365 mDebugDDMS = 0;
366 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700367 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700368 ALOGI_IF(mDebugRegion, "showupdates enabled");
369 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700370
371 property_get("debug.sf.disable_backpressure", value, "0");
372 mPropagateBackpressure = !atoi(value);
373 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700374
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800375 property_get("debug.sf.enable_hwc_vds", value, "0");
376 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800377 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800378
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800379 property_get("ro.sf.disable_triple_buffer", value, "1");
380 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800381 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700382
Yiwei Zhang243b3782018-05-15 17:40:04 -0700383 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700384 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
385 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
386
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200387 property_get("debug.sf.early_phase_offset_ns", value, "-1");
388 const int earlySfOffsetNs = atoi(value);
389
390 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
391 const int earlyGlSfOffsetNs = atoi(value);
392
393 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
394 const int earlyAppOffsetNs = atoi(value);
395
396 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
397 const int earlyGlAppOffsetNs = atoi(value);
398
Ana Krulec98b5b242018-08-10 15:03:23 -0700399 property_get("debug.sf.use_scheduler", value, "0");
400 mUseScheduler = atoi(value);
401
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200402 const VSyncModulator::Offsets earlyOffsets =
403 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
404 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
405 const VSyncModulator::Offsets earlyGlOffsets =
406 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
407 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
408 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
409 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700410
Romain Guy11d63f42017-07-20 12:47:14 -0700411 // We should be reading 'persist.sys.sf.color_saturation' here
412 // but since /data may be encrypted, we need to wait until after vold
413 // comes online to attempt to read the property. The property is
414 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800415
416 if (useTrebleTestingOverride()) {
417 // Without the override SurfaceFlinger cannot connect to HIDL
418 // services that are not listed in the manifests. Considered
419 // deriving the setting from the set service name, but it
420 // would be brittle if the name that's not 'default' is used
421 // for production purposes later on.
422 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
423 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426void SurfaceFlinger::onFirstRef()
427{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800428 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429}
430
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431SurfaceFlinger::~SurfaceFlinger()
432{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800433}
434
Dan Stozac7014012014-02-14 15:03:43 -0800435void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800436{
437 // the window manager died on us. prepare its eulogy.
438
Andy McFadden13a082e2012-08-24 10:16:42 -0700439 // restore initial conditions (default device unblank, etc)
440 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800441
442 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700443 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800444}
445
Robert Carr1db73f62016-12-21 12:58:51 -0800446static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700447 status_t err = client->initCheck();
448 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800449 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450 }
Robert Carr1db73f62016-12-21 12:58:51 -0800451 return nullptr;
452}
453
454sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
455 return initClient(new Client(this));
456}
457
458sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
459 const sp<IGraphicBufferProducer>& gbp) {
460 if (authenticateSurfaceTexture(gbp) == false) {
461 return nullptr;
462 }
463 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
464 if (layer == nullptr) {
465 return nullptr;
466 }
467
468 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800469}
470
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700471sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
472 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700473{
474 class DisplayToken : public BBinder {
475 sp<SurfaceFlinger> flinger;
476 virtual ~DisplayToken() {
477 // no more references, this display must be terminated
478 Mutex::Autolock _l(flinger->mStateLock);
479 flinger->mCurrentState.displays.removeItem(this);
480 flinger->setTransactionFlags(eDisplayTransactionNeeded);
481 }
482 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700483 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700484 : flinger(flinger) {
485 }
486 };
487
488 sp<BBinder> token = new DisplayToken(this);
489
490 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700491 DisplayDeviceState info;
492 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700493 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700494 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800496 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 return token;
498}
499
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700500void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700501 Mutex::Autolock _l(mStateLock);
502
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700503 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700505 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700506 return;
507 }
508
509 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700510 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700511 ALOGE("destroyDisplay called for non-virtual display");
512 return;
513 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700514 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700515 mCurrentState.displays.removeItemsAt(idx);
516 setTransactionFlags(eDisplayTransactionNeeded);
517}
518
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700520 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800522 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700523 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700524 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700525}
526
Ady Abraham37965d42018-11-01 13:43:32 -0700527status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
528 if (!outGetColorManagement) {
529 return BAD_VALUE;
530 }
531 *outGetColorManagement = useColorManagement;
532 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700533}
534
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800535void SurfaceFlinger::bootFinished()
536{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700537 if (mStartPropertySetThread->join() != NO_ERROR) {
538 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800539 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800540 const nsecs_t now = systemTime();
541 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000542 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700543
544 // wait patiently for the window manager death
545 const String16 name("window");
546 sp<IBinder> window(defaultServiceManager()->getService(name));
547 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700548 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549 }
550
Steven Thomas050b2c82017-03-06 11:45:16 -0800551 if (mVrFlinger) {
552 mVrFlinger->OnBootFinished();
553 }
554
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700556 // formerly we would just kill the process, but we now ask it to exit so it
557 // can choose where to stop the animation.
558 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700559
560 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
561 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
562 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700563
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800564 postMessageAsync(new LambdaMessage([this] {
565 readPersistentProperties();
566 mBootStage = BootStage::FINISHED;
567 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800568}
569
Dan Stoza436ccf32018-06-21 12:10:12 -0700570uint32_t SurfaceFlinger::getNewTexture() {
571 {
572 std::lock_guard lock(mTexturePoolMutex);
573 if (!mTexturePool.empty()) {
574 uint32_t name = mTexturePool.back();
575 mTexturePool.pop_back();
576 ATRACE_INT("TexturePoolSize", mTexturePool.size());
577 return name;
578 }
579
580 // The pool was too small, so increase it for the future
581 ++mTexturePoolSize;
582 }
583
584 // The pool was empty, so we need to get a new texture name directly using a
585 // blocking call to the main thread
586 uint32_t name = 0;
587 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
588 return name;
589}
590
Mathias Agopian3f844832013-08-07 21:24:32 -0700591void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700592 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700593}
594
Wei Wangf9b05ee2017-07-19 20:59:39 -0700595// Do not call property_set on main thread which will be blocked by init
596// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700597void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700598 ALOGI( "SurfaceFlinger's main thread ready to run. "
599 "Initializing graphics H/W...");
600
Thierry Strudel2924d012017-08-14 15:19:37 -0700601 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900602
Steven Thomasb02664d2017-07-26 18:48:28 -0700603 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800604
Steven Thomasb02664d2017-07-26 18:48:28 -0700605 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700606 if (mUseScheduler) {
Lloyd Pique90c115d2018-09-18 21:39:42 -0700607 mScheduler = getFactory().createScheduler(
Ana Krulece588e312018-09-18 12:32:24 -0700608 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Ana Krulec98b5b242018-08-10 15:03:23 -0700609 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700610 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700611 [this] { resyncWithRateLimit(); },
612 impl::EventThread::InterceptVSyncsCallback());
613 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700614 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700615 [this] { resyncWithRateLimit(); },
616 [this](nsecs_t timestamp) {
617 mInterceptor->saveVSyncEvent(timestamp);
618 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800619
Ana Krulec98b5b242018-08-10 15:03:23 -0700620 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700621 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
622 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700623 } else {
624 mEventThreadSource =
625 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
626 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
627 mEventThread =
628 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
629 [this] { resyncWithRateLimit(); },
630 impl::EventThread::InterceptVSyncsCallback(),
631 "appEventThread");
632 mSfEventThreadSource =
633 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
634 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
635
636 mSFEventThread =
637 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
638 [this] { resyncWithRateLimit(); },
639 [this](nsecs_t timestamp) {
640 mInterceptor->saveVSyncEvent(timestamp);
641 },
642 "sfEventThread");
643 mEventQueue->setEventThread(mSFEventThread.get());
644 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
645 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800646
Steven Thomasb02664d2017-07-26 18:48:28 -0700647 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700648 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700649 renderEngineFeature |= (useColorManagement ?
650 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700651 renderEngineFeature |= (useContextPriority ?
652 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700653
654 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
655 getBE().mRenderEngine =
Peiyong Linc6780972018-10-28 15:24:08 -0700656 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
657 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800658 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700659
660 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
661 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700662 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700663 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800664 // Process any initial hotplug and resulting display changes.
665 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700666 const auto display = getDefaultDisplayDeviceLocked();
667 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
668 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
669 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800670
Lloyd Piquefcd86612017-12-14 17:15:36 -0800671 // make the default display GLContext current so that we can create textures
672 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700673 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800674
Steven Thomas050b2c82017-03-06 11:45:16 -0800675 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700676 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700677 // This callback is called from the vr flinger dispatch thread. We
678 // need to call signalTransaction(), which requires holding
679 // mStateLock when we're not on the main thread. Acquiring
680 // mStateLock from the vr flinger dispatch thread might trigger a
681 // deadlock in surface flinger (see b/66916578), so post a message
682 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700683 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700684 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
685 mVrFlingerRequestsDisplay = requestDisplay;
686 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700687 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800688 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700689 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
690 getHwComposer()
691 .getHwcDisplayId(display->getId())
692 .value_or(0),
693 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800694 if (!mVrFlinger) {
695 ALOGE("Failed to start vrflinger");
696 }
697 }
698
Lloyd Pique90c115d2018-09-18 21:39:42 -0700699 mEventControlThread = getFactory().createEventControlThread(
Lloyd Pique379adc12018-01-22 17:31:47 -0800700 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700701
Mathias Agopian92a979a2012-08-02 18:32:23 -0700702 // initialize our drawing state
703 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700704
Andy McFadden13a082e2012-08-24 10:16:42 -0700705 // set initial conditions (e.g. unblank default device)
706 initializeDisplays();
707
David Sodmanbc815282017-11-05 18:57:52 -0800708 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700709
Wei Wangf9b05ee2017-07-19 20:59:39 -0700710 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700711
712 const bool presentFenceReliable =
713 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
714 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700715
716 if (mStartPropertySetThread->Start() != NO_ERROR) {
717 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800718 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800719
Chia-I Wud49d6692018-06-27 07:17:41 +0800720 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
721 // is used to saturate legacy sRGB content. However, to make sure the same color under
722 // Display P3 will be saturated to the same color, we intentionally break the API spec
723 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
724 // such saturation matrix on Display P3 is understood fully, the API should always return
725 // identify matrix.
726 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
727 Dataspace::SRGB_LINEAR);
728
729 // we will apply this on Display P3.
730 if (mEnhancedSaturationMatrix != mat4()) {
731 ColorSpace srgb(ColorSpace::sRGB());
732 ColorSpace displayP3(ColorSpace::DisplayP3());
733 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
734 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
735 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
736 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800737
Dan Stoza9e56aa02015-11-02 13:00:03 -0800738 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700739}
740
Romain Guy11d63f42017-07-20 12:47:14 -0700741void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700742 Mutex::Autolock _l(mStateLock);
743
Romain Guy11d63f42017-07-20 12:47:14 -0700744 char value[PROPERTY_VALUE_MAX];
745
746 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800747 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700748 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800749 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100750
751 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700752 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700753}
754
Mathias Agopiana67e4182012-06-19 17:26:12 -0700755void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800756 // Start boot animation service by setting a property mailbox
757 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700758 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800759 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700760 if (mStartPropertySetThread->join() != NO_ERROR) {
761 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800762 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700763}
764
Mathias Agopian875d8e12013-06-07 15:35:48 -0700765size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800766 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700767}
768
Mathias Agopian875d8e12013-06-07 15:35:48 -0700769size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800770 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700771}
772
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800773// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800774
Jamie Gennis582270d2011-08-17 18:19:00 -0700775bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800776 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800777 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800778 return authenticateSurfaceTextureLocked(bufferProducer);
779}
780
781bool SurfaceFlinger::authenticateSurfaceTextureLocked(
782 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800783 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800784 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800785}
786
Brian Anderson6b376712017-04-04 10:51:39 -0700787status_t SurfaceFlinger::getSupportedFrameTimestamps(
788 std::vector<FrameEvent>* outSupported) const {
789 *outSupported = {
790 FrameEvent::REQUESTED_PRESENT,
791 FrameEvent::ACQUIRE,
792 FrameEvent::LATCH,
793 FrameEvent::FIRST_REFRESH_START,
794 FrameEvent::LAST_REFRESH_START,
795 FrameEvent::GPU_COMPOSITION_DONE,
796 FrameEvent::DEQUEUE_READY,
797 FrameEvent::RELEASE,
798 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700799 ConditionalLock _l(mStateLock,
800 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700801 if (!getHwComposer().hasCapability(
802 HWC2::Capability::PresentFenceIsNotReliable)) {
803 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
804 }
805 return NO_ERROR;
806}
807
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700808status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
809 Vector<DisplayInfo>* configs) {
810 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 return BAD_VALUE;
812 }
813
Jesse Hall692c7232012-11-08 15:41:56 -0800814 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700815 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
816 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700817 type = i;
818 break;
819 }
820 }
821
822 if (type < 0) {
823 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700824 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 // TODO: Not sure if display density should handled by SF any longer
827 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700828 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700830 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800831 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700832 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 }
834 return density;
835 }
836 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700839 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 return getDensityFromProperty("ro.sf.lcd_density"); }
841 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700842
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700844
Steven Thomas6d8110b2017-08-31 18:24:21 -0700845 ConditionalLock _l(mStateLock,
846 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800847 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 DisplayInfo info = DisplayInfo();
849
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850 float xdpi = hwConfig->getDpiX();
851 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700852
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700853 info.w = hwConfig->getWidth();
854 info.h = hwConfig->getHeight();
855 // Default display viewport to display width and height
856 info.viewportW = info.w;
857 info.viewportH = info.h;
858
Dan Stoza7f7da322014-05-02 15:26:25 -0700859 if (type == DisplayDevice::DISPLAY_PRIMARY) {
860 // The density of the device is provided by a build property
861 float density = Density::getBuildDensity() / 160.0f;
862 if (density == 0) {
863 // the build doesn't provide a density -- this is wrong!
864 // use xdpi instead
865 ALOGE("ro.sf.lcd_density must be defined as a build property");
866 density = xdpi / 160.0f;
867 }
868 if (Density::getEmuDensity()) {
869 // if "qemu.sf.lcd_density" is specified, it overrides everything
870 xdpi = ydpi = density = Density::getEmuDensity();
871 density /= 160.0f;
872 }
873 info.density = density;
874
875 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700876 const auto display = getDefaultDisplayDeviceLocked();
877 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700878
879 // This is for screenrecord
880 const Rect viewport = display->getViewport();
881 if (viewport.isValid()) {
882 info.viewportW = uint32_t(viewport.getWidth());
883 info.viewportH = uint32_t(viewport.getHeight());
884 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700885 } else {
886 // TODO: where should this value come from?
887 static const int TV_DENSITY = 213;
888 info.density = TV_DENSITY / 160.0f;
889 info.orientation = 0;
890 }
891
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 info.xdpi = xdpi;
893 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900895 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896
Andy McFadden91b2ca82014-06-13 14:04:23 -0700897 // This is how far in advance a buffer must be queued for
898 // presentation at a given time. If you want a buffer to appear
899 // on the screen at time N, you must submit the buffer before
900 // (N - presentationDeadline).
901 //
902 // Normally it's one full refresh period (to give SF a chance to
903 // latch the buffer), but this can be reduced by configuring a
904 // DispSync offset. Any additional delays introduced by the hardware
905 // composer or panel must be accounted for here.
906 //
907 // We add an additional 1ms to allow for processing time and
908 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800909 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800910 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700911
912 // All non-virtual displays are currently considered secure.
913 info.secure = true;
914
Iris Chang7501ed62018-04-30 14:45:42 +0800915 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700916 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800917 std::swap(info.w, info.h);
918 }
919
Michael Wright28f24d02016-07-12 13:30:53 -0700920 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700921 }
922
Dan Stoza7f7da322014-05-02 15:26:25 -0700923 return NO_ERROR;
924}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700925
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700926status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
927 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700928 return BAD_VALUE;
929 }
930
Ana Krulece588e312018-09-18 12:32:24 -0700931 // FIXME for now we always return stats for the primary display.
932 if (mUseScheduler) {
933 mScheduler->getDisplayStatInfo(stats);
934 } else {
935 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
936 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
937 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700938 return NO_ERROR;
939}
940
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700941int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
942 const auto display = getDisplayDevice(displayToken);
943 if (!display) {
944 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800945 return BAD_VALUE;
946 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700947
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700948 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700949}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
952 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700953 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700954 return;
955 }
956
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700957 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700958 ALOGW("Trying to set config for virtual display");
959 return;
960 }
961
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962 display->setActiveConfig(mode);
963 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964}
965
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700966status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700967 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700968 Vector<DisplayInfo> configs;
969 getDisplayConfigs(displayToken, &configs);
970 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
971 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
972 configs.size());
973 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700974 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700975 const auto display = getDisplayDevice(displayToken);
976 if (!display) {
977 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
978 displayToken.get());
979 } else if (display->isVirtual()) {
980 ALOGW("Attempt to set active config %d for virtual display", mode);
981 } else {
982 setActiveConfigInternal(display, mode);
983 }
984 }));
985
Mathias Agopian888c8222012-08-04 21:10:38 -0700986 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700987}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700988status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
989 Vector<ColorMode>* outColorModes) {
990 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700991 return BAD_VALUE;
992 }
993
Michael Wright28f24d02016-07-12 13:30:53 -0700994 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700995 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
996 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700997 type = i;
998 break;
999 }
1000 }
1001
1002 if (type < 0) {
1003 return type;
1004 }
1005
Peiyong Lina52f0292018-03-14 17:26:31 -07001006 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001007 {
1008 ConditionalLock _l(mStateLock,
1009 std::this_thread::get_id() != mMainThreadId);
1010 modes = getHwComposer().getColorModes(type);
1011 }
Michael Wright28f24d02016-07-12 13:30:53 -07001012 outColorModes->clear();
1013 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1014
1015 return NO_ERROR;
1016}
1017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1019 if (const auto display = getDisplayDevice(displayToken)) {
1020 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001021 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001022 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001023}
1024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1026 Dataspace dataSpace, RenderIntent renderIntent) {
1027 ColorMode currentMode = display->getActiveColorMode();
1028 Dataspace currentDataSpace = display->getCompositionDataSpace();
1029 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001030
Peiyong Lin38e9a562018-04-10 16:24:20 -07001031 if (mode == currentMode && dataSpace == currentDataSpace &&
1032 renderIntent == currentRenderIntent) {
1033 return;
1034 }
1035
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001036 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001037 ALOGW("Trying to set config for virtual display");
1038 return;
1039 }
1040
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001041 display->setActiveColorMode(mode);
1042 display->setCompositionDataSpace(dataSpace);
1043 display->setActiveRenderIntent(renderIntent);
1044 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001045
1046 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1048 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001049}
1050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001052 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001053 Vector<ColorMode> modes;
1054 getDisplayColorModes(displayToken, &modes);
1055 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1056 if (mode < ColorMode::NATIVE || !exists) {
1057 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1058 decodeColorMode(mode).c_str(), mode, displayToken.get());
1059 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001060 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001061 const auto display = getDisplayDevice(displayToken);
1062 if (!display) {
1063 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1064 decodeColorMode(mode).c_str(), mode, displayToken.get());
1065 } else if (display->isVirtual()) {
1066 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1067 decodeColorMode(mode).c_str(), mode);
1068 } else {
1069 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1070 RenderIntent::COLORIMETRIC);
1071 }
1072 }));
1073
Michael Wright28f24d02016-07-12 13:30:53 -07001074 return NO_ERROR;
1075}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001076
Svetoslavd85084b2014-03-20 10:28:31 -07001077status_t SurfaceFlinger::clearAnimationFrameStats() {
1078 Mutex::Autolock _l(mStateLock);
1079 mAnimFrameTracker.clearStats();
1080 return NO_ERROR;
1081}
1082
1083status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1084 Mutex::Autolock _l(mStateLock);
1085 mAnimFrameTracker.getStats(outStats);
1086 return NO_ERROR;
1087}
1088
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001089status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1090 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001091 Mutex::Autolock _l(mStateLock);
1092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001093 const auto display = getDisplayDeviceLocked(displayToken);
1094 if (!display) {
1095 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001096 return BAD_VALUE;
1097 }
1098
Peiyong Linfb069302018-04-25 14:34:31 -07001099 // At this point the DisplayDeivce should already be set up,
1100 // meaning the luminance information is already queried from
1101 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001102 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001103 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1104 capabilities.getDesiredMaxLuminance(),
1105 capabilities.getDesiredMaxAverageLuminance(),
1106 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001107
1108 return NO_ERROR;
1109}
1110
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001111status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001112 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001113 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001114
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 if (mInjectVSyncs == enable) {
1116 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001117 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001118
Ana Krulec98b5b242018-08-10 15:03:23 -07001119 // TODO(akrulec): Part of the Injector should be refactored, so that it
1120 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001121 if (enable) {
1122 ALOGV("VSync Injections enabled");
1123 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001124 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001125 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001126 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001127 impl::EventThread::InterceptVSyncsCallback(),
1128 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001129 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001130 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001131 } else {
1132 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001133 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001134 }
1135
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001136 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001137 }));
1138
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001139 return NO_ERROR;
1140}
1141
1142status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001143 Mutex::Autolock _l(mStateLock);
1144
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001145 if (!mInjectVSyncs) {
1146 ALOGE("VSync Injections not enabled");
1147 return BAD_VALUE;
1148 }
1149 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1150 ALOGV("Injecting VSync inside SurfaceFlinger");
1151 mVSyncInjector->onInjectSyncEvent(when);
1152 }
1153 return NO_ERROR;
1154}
1155
Lloyd Pique755e3192018-01-31 16:46:15 -08001156status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1157 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001158 // Try to acquire a lock for 1s, fail gracefully
1159 const status_t err = mStateLock.timedLock(s2ns(1));
1160 const bool locked = (err == NO_ERROR);
1161 if (!locked) {
1162 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1163 return TIMED_OUT;
1164 }
1165
1166 outLayers->clear();
1167 mCurrentState.traverseInZOrder([&](Layer* layer) {
1168 outLayers->push_back(layer->getLayerDebugInfo());
1169 });
1170
1171 mStateLock.unlock();
1172 return NO_ERROR;
1173}
1174
Peiyong Linc6780972018-10-28 15:24:08 -07001175status_t SurfaceFlinger::getCompositionPreference(
1176 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1177 Dataspace* outWideColorGamutDataspace,
1178 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001179 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001180 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001181 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001182 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001183 return NO_ERROR;
1184}
1185
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001186// ----------------------------------------------------------------------------
1187
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001188sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1189 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001190 if (mUseScheduler) {
1191 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1192 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1193 } else {
1194 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1195 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001196 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001197 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1198 return mSFEventThread->createEventConnection();
1199 } else {
1200 return mEventThread->createEventConnection();
1201 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001202 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001203}
1204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001205// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001206
1207void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001208 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001209}
1210
1211void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001212 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001213}
1214
1215void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001216 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001217}
1218
1219void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001220 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001221 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001222}
1223
1224status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001225 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001226 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001227}
1228
1229status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001230 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001231 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001232 if (res == NO_ERROR) {
1233 msg->wait();
1234 }
1235 return res;
1236}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001237
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001238void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001239 do {
1240 waitForEvent();
1241 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001242}
1243
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001244void SurfaceFlinger::enableHardwareVsync() {
1245 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001246 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001247 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001248 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001249 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001250 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251}
1252
Jesse Hall948fe0c2013-10-14 12:56:09 -07001253void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254 Mutex::Autolock _l(mHWVsyncLock);
1255
Jesse Hall948fe0c2013-10-14 12:56:09 -07001256 if (makeAvailable) {
1257 mHWVsyncAvailable = true;
1258 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001259 // Hardware vsync is not currently available, so abort the resync
1260 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001261 return;
1262 }
1263
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001264 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1265 if (!getHwComposer().isConnected(displayId)) {
1266 return;
1267 }
1268
1269 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001270 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001271
Ana Krulece588e312018-09-18 12:32:24 -07001272 if (mUseScheduler) {
1273 mScheduler->setVsyncPeriod(period);
1274 } else {
1275 mPrimaryDispSync->reset();
1276 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277
Ana Krulece588e312018-09-18 12:32:24 -07001278 if (!mPrimaryHWVsyncEnabled) {
1279 mPrimaryDispSync->beginResync();
1280 mEventControlThread->setVsyncEnabled(true);
1281 mPrimaryHWVsyncEnabled = true;
1282 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001283 }
1284}
1285
Jesse Hall948fe0c2013-10-14 12:56:09 -07001286void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001287 Mutex::Autolock _l(mHWVsyncLock);
1288 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001289 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001290 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001291 mPrimaryHWVsyncEnabled = false;
1292 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001293 if (makeUnavailable) {
1294 mHWVsyncAvailable = false;
1295 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296}
1297
Tim Murray4a4e4a22016-04-19 16:29:23 +00001298void SurfaceFlinger::resyncWithRateLimit() {
1299 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001300
1301 // No explicit locking is needed here since EventThread holds a lock while calling this method
1302 static nsecs_t sLastResyncAttempted = 0;
1303 const nsecs_t now = systemTime();
1304 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001305 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001306 }
Dan Stoza57164302017-05-08 14:03:54 -07001307 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001308}
1309
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001310void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1311 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001312 ATRACE_NAME("SF onVsync");
1313
Steven Thomas3cfac282017-02-06 12:29:30 -08001314 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001315 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001316 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001317 return;
1318 }
1319
1320 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001321 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001322 return;
1323 }
1324
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001325 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1326 // For now, we don't do anything with external display vsyncs.
1327 return;
1328 }
1329
Ana Krulece588e312018-09-18 12:32:24 -07001330 if (mUseScheduler) {
1331 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001332 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001333 bool needsHwVsync = false;
1334 { // Scope for the lock
1335 Mutex::Autolock _l(mHWVsyncLock);
1336 if (mPrimaryHWVsyncEnabled) {
1337 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1338 }
1339 }
1340
1341 if (needsHwVsync) {
1342 enableHardwareVsync();
1343 } else {
1344 disableHardwareVsync(false);
1345 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001346 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001347}
1348
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001349void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001350 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1351 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001352}
1353
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001354void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001355 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001356 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001357 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001358
Lloyd Piqueba04e622017-12-14 17:11:26 -08001359 // Ignore events that do not have the right sequenceId.
1360 if (sequenceId != getBE().mComposerSequenceId) {
1361 return;
1362 }
1363
Steven Thomasb02664d2017-07-26 18:48:28 -07001364 // Only lock if we're not on the main thread. This function is normally
1365 // called on a hwbinder thread, but for the primary display it's called on
1366 // the main thread with the state lock already held, so don't attempt to
1367 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001368 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001369
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001370 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001371
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001372 if (std::this_thread::get_id() == mMainThreadId) {
1373 // Process all pending hot plug events immediately if we are on the main thread.
1374 processDisplayHotplugEventsLocked();
1375 }
1376
Lloyd Piqueba04e622017-12-14 17:11:26 -08001377 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001378}
1379
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001380void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001381 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001382 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001384 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001385 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001386}
1387
Dan Stoza9e56aa02015-11-02 13:00:03 -08001388void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001389 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001391 getHwComposer().setVsyncEnabled(disp,
1392 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001393}
1394
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001395// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001396void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001397 if (mUseScheduler) {
1398 mScheduler->disableHardwareVsync(true);
1399 } else {
1400 disableHardwareVsync(true);
1401 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001402 // Clear the drawing state so that the logic inside of
1403 // handleTransactionLocked will fire. It will determine the delta between
1404 // mCurrentState and mDrawingState and re-apply all changes when we make the
1405 // transition.
1406 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001407 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001408 mDisplays.clear();
1409}
1410
Steven Thomas050b2c82017-03-06 11:45:16 -08001411void SurfaceFlinger::updateVrFlinger() {
1412 if (!mVrFlinger)
1413 return;
1414 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001415 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001416 return;
1417 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001418
David Sodman105b7dc2017-11-04 20:28:14 -07001419 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001420 ALOGE("Vr flinger is only supported for remote hardware composer"
1421 " service connections. Ignoring request to transition to vr"
1422 " flinger.");
1423 mVrFlingerRequestsDisplay = false;
1424 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001425 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001426
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001427 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001428
Steven Thomas0123ac62018-07-12 11:32:34 -07001429 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001430 LOG_ALWAYS_FATAL_IF(!display);
1431 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001432 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1433 // called below. Clear the reference now so we don't accidentally use it
1434 // later.
1435 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001436
Steven Thomasb02664d2017-07-26 18:48:28 -07001437 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001438 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001439 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001440
Steven Thomasb02664d2017-07-26 18:48:28 -07001441 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001442 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001443 getBE().mHwc = getFactory().createHWComposer(
1444 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001445 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001446
David Sodman105b7dc2017-11-04 20:28:14 -07001447 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1448 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001449
1450 if (vrFlingerRequestsDisplay) {
1451 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001452 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001453
1454 mVisibleRegionsDirty = true;
1455 invalidateHwcGeometry();
1456
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001457 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001458 display = getDefaultDisplayDeviceLocked();
1459 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001460 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001461
Steven Thomasb02664d2017-07-26 18:48:28 -07001462 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001463 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001464 const nsecs_t period = activeConfig->getVsyncPeriod();
1465 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001466
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001467 // The present fences returned from vr_hwc are not an accurate
1468 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001469 if (mUseScheduler) {
1470 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1471 } else {
1472 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1473 !hasSyncFramework);
1474 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001475
Steven Thomasb02664d2017-07-26 18:48:28 -07001476 // Use phase of 0 since phase is not known.
1477 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001478 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1479 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001480
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001481 resyncToHardwareVsync(false);
1482
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001483 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001484 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001485}
1486
Mathias Agopian4fec8732012-06-29 14:12:52 -07001487void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001488 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001489 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001490 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001491 bool frameMissed = !mHadClientComposition &&
1492 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001493 (mPreviousPresentFence->getSignalTime() ==
1494 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001495 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001496 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001497 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001498 mTimeStats.incrementMissedFrames();
1499 if (mPropagateBackpressure) {
1500 signalLayerUpdate();
1501 break;
1502 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001503 }
Dan Stoza50182882016-07-08 12:02:20 -07001504
Steven Thomas050b2c82017-03-06 11:45:16 -08001505 // Now that we're going to make it to the handleMessageTransaction()
1506 // call below it's safe to call updateVrFlinger(), which will
1507 // potentially trigger a display handoff.
1508 updateVrFlinger();
1509
Dan Stoza6b9454d2014-11-07 16:00:59 -08001510 bool refreshNeeded = handleMessageTransaction();
1511 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001512 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001513 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001514 // Signal a refresh if a transaction modified the window state,
1515 // a new buffer was latched, or if HWC has requested a full
1516 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001517 signalRefresh();
1518 }
1519 break;
1520 }
1521 case MessageQueue::REFRESH: {
1522 handleMessageRefresh();
1523 break;
1524 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001525 }
1526}
1527
Dan Stoza6b9454d2014-11-07 16:00:59 -08001528bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001529 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001530 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001531 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001532 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001533 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001534 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001535}
1536
Mathias Agopian4fec8732012-06-29 14:12:52 -07001537void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001538 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001539
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001540 mRefreshPending = false;
1541
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001542 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001543 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001544 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001545 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001546 for (const auto& [token, display] : mDisplays) {
1547 beginFrame(display);
1548 prepareFrame(display);
1549 doDebugFlashRegions(display, repaintEverything);
1550 doComposition(display, repaintEverything);
1551 }
1552
Adrian Roos1e1a1282017-11-01 19:05:31 +01001553 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001554 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001555
1556 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001557 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001558
Dan Stozabfbffeb2016-07-21 14:49:33 -07001559 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001560 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001561 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001562 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001563 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001564
Alec Mouri86770e52018-09-24 22:40:58 +00001565 // Setup RenderEngine sync fences if native sync is supported.
1566 if (getBE().mRenderEngine->useNativeFenceSync()) {
1567 if (mHadClientComposition) {
1568 base::unique_fd flushFence(getRenderEngine().flush());
1569 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1570 getBE().flushFence = new Fence(std::move(flushFence));
1571 } else {
1572 // Cleanup for hygiene.
1573 getBE().flushFence = Fence::NO_FENCE;
1574 }
1575 }
1576
Jorim Jaggi90535212018-05-23 23:44:06 +02001577 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001578
David Sodman7e4ae112018-02-09 15:02:28 -08001579 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001580 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001581 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001582 compositionInfo.hwc.hwcLayer = nullptr;
1583 }
David Sodmanba340492018-08-05 21:51:33 -07001584 }
David Sodman7e4ae112018-02-09 15:02:28 -08001585
1586 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001588
David Sodmanfa9b2af2017-12-24 13:28:59 -08001589
1590bool SurfaceFlinger::handleMessageInvalidate() {
1591 ATRACE_CALL();
1592 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001593}
1594
David Sodman79bba0e2018-08-05 18:07:49 -07001595void SurfaceFlinger::calculateWorkingSet() {
1596 ATRACE_CALL();
1597 ALOGV(__FUNCTION__);
1598
David Sodman79bba0e2018-08-05 18:07:49 -07001599 // build the h/w work list
1600 if (CC_UNLIKELY(mGeometryInvalid)) {
1601 mGeometryInvalid = false;
1602 for (const auto& [token, display] : mDisplays) {
1603 const auto displayId = display->getId();
1604 if (displayId >= 0) {
1605 const Vector<sp<Layer>>& currentLayers(
1606 display->getVisibleLayersSortedByZ());
1607 for (size_t i = 0; i < currentLayers.size(); i++) {
1608 const auto& layer = currentLayers[i];
1609
1610 if (!layer->hasHwcLayer(displayId)) {
1611 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1612 layer->forceClientComposition(displayId);
1613 continue;
1614 }
1615 }
1616
1617 layer->setGeometry(display, i);
1618 if (mDebugDisableHWC || mDebugRegion) {
1619 layer->forceClientComposition(displayId);
1620 }
1621 }
1622 }
1623 }
1624 }
1625
1626 // Set the per-frame data
1627 for (const auto& [token, display] : mDisplays) {
1628 const auto displayId = display->getId();
1629 if (displayId < 0) {
1630 continue;
1631 }
1632
1633 if (mDrawingState.colorMatrixChanged) {
1634 display->setColorTransform(mDrawingState.colorMatrix);
1635 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1636 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1637 "display %d: %d", displayId, result);
1638 }
1639 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1640 if (layer->isHdrY410()) {
1641 layer->forceClientComposition(displayId);
1642 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1643 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1644 !display->hasHDR10Support()) {
1645 layer->forceClientComposition(displayId);
1646 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1647 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1648 !display->hasHLGSupport()) {
1649 layer->forceClientComposition(displayId);
1650 }
1651
Peiyong Lind3788632018-09-18 16:01:31 -07001652 // TODO(b/111562338) remove when composer 2.3 is shipped.
1653 if (layer->hasColorTransform()) {
1654 layer->forceClientComposition(displayId);
1655 }
1656
David Sodman79bba0e2018-08-05 18:07:49 -07001657 if (layer->getForceClientComposition(displayId)) {
1658 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1659 layer->setCompositionType(displayId, HWC2::Composition::Client);
1660 continue;
1661 }
1662
1663 layer->setPerFrameData(display);
1664 }
1665
Peiyong Lin13effd12018-07-24 17:01:47 -07001666 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001667 ColorMode colorMode;
1668 Dataspace dataSpace;
1669 RenderIntent renderIntent;
1670 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1671 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1672 }
1673 }
1674
1675 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001676
1677 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001678 getBE().mCompositionInfo[token].clear();
1679
David Sodmanba340492018-08-05 21:51:33 -07001680 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001681 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001682 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1683 if (!layer->setHwcLayer(displayId)) {
1684 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1685 }
David Sodman15fb96e2018-01-07 10:23:24 -08001686 layer->getBE().compositionInfo.hwc.displayId = displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001687 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001688 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1689 }
1690 }
David Sodman79bba0e2018-08-05 18:07:49 -07001691}
1692
David Sodmanfa9b2af2017-12-24 13:28:59 -08001693void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001694{
1695 // is debugging enabled
1696 if (CC_LIKELY(!mDebugRegion))
1697 return;
1698
David Sodmanfa9b2af2017-12-24 13:28:59 -08001699 if (display->isPoweredOn()) {
1700 // transform the dirty region into this screen's coordinate space
1701 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1702 if (!dirtyRegion.isEmpty()) {
1703 // redraw the whole screen
1704 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705
David Sodmanfa9b2af2017-12-24 13:28:59 -08001706 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001707 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001708 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001709
David Sodmanfa9b2af2017-12-24 13:28:59 -08001710 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001711 }
1712 }
1713
David Sodmanfa9b2af2017-12-24 13:28:59 -08001714 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715
1716 if (mDebugRegion > 1) {
1717 usleep(mDebugRegion * 1000);
1718 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001719
Dominik Laskowski05275f12018-11-01 15:03:24 -07001720 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001721}
1722
Adrian Roos1e1a1282017-11-01 19:05:31 +01001723void SurfaceFlinger::doTracing(const char* where) {
1724 ATRACE_CALL();
1725 ATRACE_NAME(where);
1726 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001727 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001728 }
1729}
1730
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001731void SurfaceFlinger::logLayerStats() {
1732 ATRACE_CALL();
1733 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001734 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001735 if (display->isPrimary()) {
1736 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001737 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001738 }
1739 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001740
1741 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001742 }
1743}
1744
David Sodman2b406362017-12-15 13:33:47 -08001745void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001746{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001747 ATRACE_CALL();
1748 ALOGV("preComposition");
1749
David Sodman2b406362017-12-15 13:33:47 -08001750 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1751
Mathias Agopiancd60f992012-08-16 16:28:27 -07001752 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001753 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001754 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001755 needExtraInvalidate = true;
1756 }
Robert Carr2047fae2016-11-28 14:09:09 -08001757 });
1758
Mathias Agopiancd60f992012-08-16 16:28:27 -07001759 if (needExtraInvalidate) {
1760 signalLayerUpdate();
1761 }
1762}
1763
Ana Krulece588e312018-09-18 12:32:24 -07001764void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1765 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001766 // Update queue of past composite+present times and determine the
1767 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001768 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001769 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001770 while (!getBE().mCompositePresentTimes.empty()) {
1771 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001772 // Cached values should have been updated before calling this method,
1773 // which helps avoid duplicate syscalls.
1774 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1775 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1776 break;
1777 }
1778 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001779 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001780 }
1781
1782 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001783 while (getBE().mCompositePresentTimes.size() > 16) {
1784 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001785 }
1786
Ana Krulece588e312018-09-18 12:32:24 -07001787 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001788}
1789
Ana Krulece588e312018-09-18 12:32:24 -07001790void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1791 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001792 // Integer division and modulo round toward 0 not -inf, so we need to
1793 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001794 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1795 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1796 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001797
Brian Andersond0010582017-03-07 13:20:31 -08001798 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1799 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001800 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001801 }
1802
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001803 // Snap the latency to a value that removes scheduling jitter from the
1804 // composition and present times, which often have >1ms of jitter.
1805 // Reducing jitter is important if an app attempts to extrapolate
1806 // something (such as user input) to an accurate diasplay time.
1807 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1808 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001809 nsecs_t bias = stats.vsyncPeriod / 2;
1810 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1811 nsecs_t snappedCompositeToPresentLatency =
1812 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001813
David Sodman99974d22017-11-28 12:04:33 -08001814 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001815 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1816 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001817 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001818}
1819
David Sodman2b406362017-12-15 13:33:47 -08001820void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001821{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001822 ATRACE_CALL();
1823 ALOGV("postComposition");
1824
Brian Anderson3546a3f2016-07-14 11:51:14 -07001825 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001826 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001827 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001828 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001829 }
1830
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001831 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001832 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001833
David Sodman73beded2017-11-15 11:56:06 -08001834 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001835 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001836 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001837 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001838 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001839 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001840 } else {
1841 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1842 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001843
David Sodman73beded2017-11-15 11:56:06 -08001844 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001845 mPreviousPresentFence =
1846 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1847 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001848 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001849
Ana Krulece588e312018-09-18 12:32:24 -07001850 DisplayStatInfo stats;
1851 if (mUseScheduler) {
1852 mScheduler->getDisplayStatInfo(&stats);
1853 } else {
1854 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1855 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1856 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001857
David Sodman2b406362017-12-15 13:33:47 -08001858 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001859 // when we started doing work for this frame, but that should be okay
1860 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001861 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001862 CompositorTiming compositorTiming;
1863 {
David Sodman99974d22017-11-28 12:04:33 -08001864 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1865 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001866 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001867
Robert Carr2047fae2016-11-28 14:09:09 -08001868 mDrawingState.traverseInZOrder([&](Layer* layer) {
1869 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001870 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001871 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001872 recordBufferingStats(layer->getName().string(),
1873 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001874 }
Robert Carr2047fae2016-11-28 14:09:09 -08001875 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001876
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001877 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001878 if (mUseScheduler) {
1879 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001880 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001881 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1882 enableHardwareVsync();
1883 } else {
1884 disableHardwareVsync(false);
1885 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001886 }
1887 }
1888
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001889 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001890 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001891 if (mUseScheduler) {
1892 mScheduler->enableHardwareVsync();
1893 } else {
1894 enableHardwareVsync();
1895 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001896 }
1897 }
1898
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001899 if (mAnimCompositionPending) {
1900 mAnimCompositionPending = false;
1901
Brian Anderson4e606e32017-03-16 15:34:57 -07001902 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001903 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001904 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001905 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001906 // The HWC doesn't support present fences, so use the refresh
1907 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001908 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001909 mAnimFrameTracker.setActualPresentTime(presentTime);
1910 }
1911 mAnimFrameTracker.advanceFrame();
1912 }
Dan Stozab90cf072015-03-05 11:05:59 -08001913
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001914 mTimeStats.incrementTotalFrames();
1915 if (mHadClientComposition) {
1916 mTimeStats.incrementClientCompositionFrames();
1917 }
1918
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001919 mTimeStats.setPresentFenceGlobal(presentFenceTime);
1920
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001921 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001922 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001923 return;
1924 }
1925
1926 nsecs_t currentTime = systemTime();
1927 if (mHasPoweredOff) {
1928 mHasPoweredOff = false;
1929 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001930 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001931 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001932 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1933 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001934 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001935 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001936 }
David Sodman4a36e932017-11-07 14:29:47 -08001937 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001938 }
David Sodman4a36e932017-11-07 14:29:47 -08001939 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001940
1941 {
1942 std::lock_guard lock(mTexturePoolMutex);
1943 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1944 if (refillCount > 0) {
1945 const size_t offset = mTexturePool.size();
1946 mTexturePool.resize(mTexturePoolSize);
1947 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1948 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1949 }
1950 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001951}
1952
1953void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001954 ATRACE_CALL();
1955 ALOGV("rebuildLayerStacks");
1956
Mathias Agopiancd60f992012-08-16 16:28:27 -07001957 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001958 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001959 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001960 mVisibleRegionsDirty = false;
1961 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001962
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001963 for (const auto& pair : mDisplays) {
1964 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001965 Region opaqueRegion;
1966 Region dirtyRegion;
1967 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001968 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001969 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001970 const Rect bounds = display->getBounds();
1971 if (display->isPoweredOn()) {
1972 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001973
Jeff Sharkey76488112017-02-27 14:15:18 -07001974 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001975 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001976 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001977 Region drawRegion(tr.transform(
1978 layer->visibleNonTransparentRegion));
1979 drawRegion.andSelf(bounds);
1980 if (!drawRegion.isEmpty()) {
1981 layersSortedByZ.add(layer);
1982 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001983 // Clear out the HWC layer if this layer was
1984 // previously visible, but no longer is
1985 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001986 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001987 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001988 // WM changes display->layerStack upon sleep/awake.
1989 // Here we make sure we delete the HWC layers even if
1990 // WM changed their layer stack.
1991 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001992 }
1993
1994 // If a layer is not going to get a release fence because
1995 // it is invisible, but it is also going to release its
1996 // old buffer, add it to the list of layers needing
1997 // fences.
1998 if (hwcLayerDestroyed) {
1999 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2000 mLayersWithQueuedFrames.cend(), layer);
2001 if (found != mLayersWithQueuedFrames.cend()) {
2002 layersNeedingFences.add(layer);
2003 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002004 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002005 });
2006 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002007 display->setVisibleLayersSortedByZ(layersSortedByZ);
2008 display->setLayersNeedingFences(layersNeedingFences);
2009 display->undefinedRegion.set(bounds);
2010 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2011 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002012 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002013 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002014}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002015
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002016// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002017// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002018// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002019// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002020// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002021// The returned HDR data space is one of
2022// - Dataspace::UNKNOWN
2023// - Dataspace::BT2020_HLG
2024// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002025Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2026 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002027 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002028 *outHdrDataSpace = Dataspace::UNKNOWN;
2029
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002030 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002031 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002032 case Dataspace::V0_SCRGB:
2033 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002034 case Dataspace::BT2020:
2035 case Dataspace::BT2020_ITU:
2036 case Dataspace::BT2020_LINEAR:
2037 case Dataspace::DISPLAY_BT2020:
2038 bestDataSpace = Dataspace::DISPLAY_BT2020;
2039 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002040 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002041 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002042 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002043 case Dataspace::BT2020_PQ:
2044 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002045 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002046 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002047 case Dataspace::BT2020_HLG:
2048 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002049 // When there's mixed PQ content and HLG content, we set the HDR
2050 // data space to be BT2020_PQ and convert HLG to PQ.
2051 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2052 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002053 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002054 break;
2055 default:
2056 break;
2057 }
Romain Guy54f154a2017-10-24 21:40:32 +01002058 }
2059
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002060 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002061}
2062
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002063// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002064void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2065 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002066 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2067 *outMode = ColorMode::NATIVE;
2068 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002069 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002070 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002071 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002072
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002073 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002074 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002075
Peiyong Lindfde5112018-06-05 10:58:41 -07002076 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002077 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002078 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002079 if (isHdr) {
2080 bestDataSpace = hdrDataSpace;
2081 }
2082
Chia-I Wu0d711262018-05-21 15:19:35 -07002083 RenderIntent intent;
2084 switch (mDisplayColorSetting) {
2085 case DisplayColorSetting::MANAGED:
2086 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002087 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002088 break;
2089 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002090 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002091 break;
2092 default: // vendor display color setting
2093 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2094 break;
2095 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002096
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002097 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002098}
2099
David Sodmanfa9b2af2017-12-24 13:28:59 -08002100void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002101{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002102 bool dirty = !display->getDirtyRegion(false).isEmpty();
2103 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2104 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002105
David Sodmanfa9b2af2017-12-24 13:28:59 -08002106 // If nothing has changed (!dirty), don't recompose.
2107 // If something changed, but we don't currently have any visible layers,
2108 // and didn't when we last did a composition, then skip it this time.
2109 // The second rule does two things:
2110 // - When all layers are removed from a display, we'll emit one black
2111 // frame, then nothing more until we get new layers.
2112 // - When a display is created with a private layer stack, we won't
2113 // emit any black frames until a layer is added to the layer stack.
2114 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002115
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002116 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2117 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002118 mustRecompose ? "doing" : "skipping",
2119 dirty ? "+" : "-",
2120 empty ? "+" : "-",
2121 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002122
David Sodmanfa9b2af2017-12-24 13:28:59 -08002123 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002124
David Sodmanfa9b2af2017-12-24 13:28:59 -08002125 if (mustRecompose) {
2126 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002127 }
2128}
2129
David Sodmanfa9b2af2017-12-24 13:28:59 -08002130void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002131{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002132 if (!display->isPoweredOn()) {
2133 return;
David Sodman2b406362017-12-15 13:33:47 -08002134 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002135
Dominik Laskowski05275f12018-11-01 15:03:24 -07002136 status_t result = display->prepareFrame(getHwComposer(),
2137 getBE().mCompositionInfo[display->getDisplayToken()]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002138 ALOGE_IF(result != NO_ERROR,
2139 "prepareFrame for display %d failed:"
2140 " %d (%s)",
2141 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002142}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002143
David Sodmanfa9b2af2017-12-24 13:28:59 -08002144void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002145 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002146 ALOGV("doComposition");
2147
David Sodmanfa9b2af2017-12-24 13:28:59 -08002148 if (display->isPoweredOn()) {
2149 // transform the dirty region into this screen's coordinate space
2150 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002151
David Sodmanfa9b2af2017-12-24 13:28:59 -08002152 // repaint the framebuffer (if needed)
2153 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002154
David Sodmanfa9b2af2017-12-24 13:28:59 -08002155 display->dirtyRegion.clear();
2156 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002157 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002158 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002159}
2160
David Sodmanfa9b2af2017-12-24 13:28:59 -08002161void SurfaceFlinger::postFrame()
2162{
2163 // |mStateLock| not needed as we are on the main thread
2164 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2165 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2166 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2167 logFrameStats();
2168 }
2169 }
2170}
2171
2172void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002173{
Mathias Agopian841cde52012-03-01 15:44:37 -08002174 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002175 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002176
David Sodmanfa9b2af2017-12-24 13:28:59 -08002177 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002178
David Sodmanfa9b2af2017-12-24 13:28:59 -08002179 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002180 const auto displayId = display->getId();
2181 if (displayId >= 0) {
2182 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002183 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002184 display->onSwapBuffersCompleted();
2185 display->makeCurrent();
David Sodman15094112018-10-11 09:39:37 -07002186 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002187 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002188
Chia-I Wu7b549592017-11-15 09:14:57 -08002189 // The layer buffer from the previous frame (if any) is released
2190 // by HWC only when the release fence from this frame (if any) is
2191 // signaled. Always get the release fence from HWC first.
David Sodman15094112018-10-11 09:39:37 -07002192 auto hwcLayer = layer->getHwcLayer(displayId);
2193 if (displayId >= 0) {
2194 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002195 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002196
2197 // If the layer was client composited in the previous frame, we
2198 // need to merge with the previous client target acquire fence.
2199 // Since we do not track that, always merge with the current
2200 // client target acquire fence when it is available, even though
2201 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002202 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002203 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002204 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002205 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002206
David Sodman15094112018-10-11 09:39:37 -07002207 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002208 }
Chia-I Wu83806892017-11-16 10:50:20 -08002209
2210 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002211 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002212 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002213 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002214 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002215 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002216 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002217 }
2218 }
2219
Dominik Laskowski7e045462018-05-30 13:02:02 -07002220 if (displayId >= 0) {
2221 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002222 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002223 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002224}
2225
Mathias Agopian87baae12012-07-31 12:38:26 -07002226void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002227{
Mathias Agopian841cde52012-03-01 15:44:37 -08002228 ATRACE_CALL();
2229
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002230 // here we keep a copy of the drawing state (that is the state that's
2231 // going to be overwritten by handleTransactionLocked()) outside of
2232 // mStateLock so that the side-effects of the State assignment
2233 // don't happen with mStateLock held (which can cause deadlocks).
2234 State drawingState(mDrawingState);
2235
Mathias Agopianca4d3602011-05-19 15:38:14 -07002236 Mutex::Autolock _l(mStateLock);
2237 const nsecs_t now = systemTime();
2238 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002239
Mathias Agopianca4d3602011-05-19 15:38:14 -07002240 // Here we're guaranteed that some transaction flags are set
2241 // so we can call handleTransactionLocked() unconditionally.
2242 // We call getTransactionFlags(), which will also clear the flags,
2243 // with mStateLock held to guarantee that mCurrentState won't change
2244 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002245
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002246 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002247 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002248 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002249
Mathias Agopianca4d3602011-05-19 15:38:14 -07002250 mLastTransactionTime = systemTime() - now;
2251 mDebugInTransaction = 0;
2252 invalidateHwcGeometry();
2253 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002254}
2255
Dominik Laskowski7e045462018-05-30 13:02:02 -07002256DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002257 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002258 // Figure out whether the event is for the primary display or an
2259 // external display by matching the Hwc display id against one for a
2260 // connected display. If we did not find a match, we then check what
2261 // displays are not already connected to determine the type. If we don't
2262 // have a connected primary display, we assume the new display is meant to
2263 // be the primary display, and then if we don't have an external display,
2264 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002265 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2266 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002267 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002268 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002269 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002270 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002271 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002272 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002273 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002274 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002275 return DisplayDevice::DISPLAY_EXTERNAL;
2276 }
2277
2278 return DisplayDevice::DISPLAY_ID_INVALID;
2279}
2280
Lloyd Piqueba04e622017-12-14 17:11:26 -08002281void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2282 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002283 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002284 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002285 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002286 continue;
2287 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002288
2289 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2290 ALOGE("External displays are not supported by the vr hardware composer.");
2291 continue;
2292 }
2293
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002294 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002295 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002296 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002297 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002298 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002299
2300 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002301 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002302 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002303 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002304 DisplayDeviceState info;
2305 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002306 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2307 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002308 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002309 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002310 mInterceptor->saveDisplayCreation(info);
2311 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002312 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002313 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002314
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002315 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002316 if (idx >= 0) {
2317 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002318 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002319 mCurrentState.displays.removeItemsAt(idx);
2320 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002321 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002322 }
2323
2324 processDisplayChangesLocked();
2325 }
2326
2327 mPendingHotplugEvents.clear();
2328}
2329
Lloyd Pique99d3da52018-01-22 17:48:03 -08002330sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002331 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002332 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002333 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2334 creationArgs.isSecure = state.isSecure;
2335 creationArgs.displaySurface = dispSurface;
2336 creationArgs.hasWideColorGamut = false;
2337 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002338
Peiyong Lin13effd12018-07-24 17:01:47 -07002339 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002340 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002341 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002342 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002343 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002344 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002345
Dominik Laskowski7e045462018-05-30 13:02:02 -07002346 std::vector<RenderIntent> renderIntents =
2347 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002348 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002349 }
tangrobin6753a022018-08-10 10:58:54 +08002350 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002351
tangrobin6753a022018-08-10 10:58:54 +08002352 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002353 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2354 creationArgs.supportedPerFrameMetadata =
2355 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002356 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002357
Lloyd Pique90c115d2018-09-18 21:39:42 -07002358 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002359 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002360 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002361
2362 /*
2363 * Create our display's surface
2364 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002365 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002366 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002367 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002368 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002369 creationArgs.displayWidth = renderSurface->getWidth();
2370 creationArgs.displayHeight = renderSurface->getHeight();
2371 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002372
2373 // Make sure that composition can never be stalled by a virtual display
2374 // consumer that isn't processing buffers fast enough. We have to do this
2375 // in two places:
2376 // * Here, in case the display is composed entirely by HWC.
2377 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2378 // window's swap interval in eglMakeCurrent, so they'll override the
2379 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002380 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002381 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2382 }
2383
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002384 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2385 ? primaryDisplayOrientation
2386 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002387
Lloyd Pique99d3da52018-01-22 17:48:03 -08002388 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002389 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002390
Lloyd Pique90c115d2018-09-18 21:39:42 -07002391 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002392
2393 if (maxFrameBufferAcquiredBuffers >= 3) {
2394 nativeWindowSurface->preallocateBuffers();
2395 }
2396
2397 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002398 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002399 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002400 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002401 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002402 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002403 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002404 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002405 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002406 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002407 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002408 display->setLayerStack(state.layerStack);
2409 display->setProjection(state.orientation, state.viewport, state.frame);
2410 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002411
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002412 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002413}
2414
Lloyd Pique347200f2017-12-14 17:00:15 -08002415void SurfaceFlinger::processDisplayChangesLocked() {
2416 // here we take advantage of Vector's copy-on-write semantics to
2417 // improve performance by skipping the transaction entirely when
2418 // know that the lists are identical
2419 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2420 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2421 if (!curr.isIdenticalTo(draw)) {
2422 mVisibleRegionsDirty = true;
2423 const size_t cc = curr.size();
2424 size_t dc = draw.size();
2425
2426 // find the displays that were removed
2427 // (ie: in drawing state but not in current state)
2428 // also handle displays that changed
2429 // (ie: displays that are in both lists)
2430 for (size_t i = 0; i < dc;) {
2431 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2432 if (j < 0) {
2433 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002434 // Call makeCurrent() on the primary display so we can
2435 // be sure that nothing associated with this display
2436 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002437 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2438 defaultDisplay->makeCurrent();
2439 }
2440 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2441 display->disconnect(getHwComposer());
2442 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002443 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002444 if (mUseScheduler) {
2445 mScheduler->hotplugReceived(mAppConnectionHandle,
2446 EventThread::DisplayType::Primary, false);
2447 } else {
2448 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2449 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002450 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002451 if (mUseScheduler) {
2452 mScheduler->hotplugReceived(mAppConnectionHandle,
2453 EventThread::DisplayType::External, false);
2454 } else {
2455 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2456 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002457 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002458 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002459 } else {
2460 // this display is in both lists. see if something changed.
2461 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002462 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002463 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2464 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2465 if (state_binder != draw_binder) {
2466 // changing the surface is like destroying and
2467 // recreating the DisplayDevice, so we just remove it
2468 // from the drawing state, so that it get re-added
2469 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002470 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2471 display->disconnect(getHwComposer());
2472 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002473 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002474 mDrawingState.displays.removeItemsAt(i);
2475 dc--;
2476 // at this point we must loop to the next item
2477 continue;
2478 }
2479
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002480 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002481 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002482 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002483 }
2484 if ((state.orientation != draw[i].orientation) ||
2485 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002486 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002487 }
2488 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002489 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002490 }
2491 }
2492 }
2493 ++i;
2494 }
2495
2496 // find displays that were added
2497 // (ie: in current state but not in drawing state)
2498 for (size_t i = 0; i < cc; i++) {
2499 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2500 const DisplayDeviceState& state(curr[i]);
2501
2502 sp<DisplaySurface> dispSurface;
2503 sp<IGraphicBufferProducer> producer;
2504 sp<IGraphicBufferProducer> bqProducer;
2505 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002506 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002507
Dominik Laskowski7e045462018-05-30 13:02:02 -07002508 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002509 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002510 // Virtual displays without a surface are dormant:
2511 // they have external state (layer stack, projection,
2512 // etc.) but no internal state (i.e. a DisplayDevice).
2513 if (state.surface != nullptr) {
2514 // Allow VR composer to use virtual displays.
2515 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2516 int width = 0;
2517 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2518 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2519 int height = 0;
2520 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2521 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2522 int intFormat = 0;
2523 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2524 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002525 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002526
Dominik Laskowski7e045462018-05-30 13:02:02 -07002527 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2528 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002529 }
2530
2531 // TODO: Plumb requested format back up to consumer
2532
2533 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002534 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002535 bqProducer, bqConsumer,
2536 state.displayName);
2537
2538 dispSurface = vds;
2539 producer = vds;
2540 }
2541 } else {
2542 ALOGE_IF(state.surface != nullptr,
2543 "adding a supported display, but rendering "
2544 "surface is provided (%p), ignoring it",
2545 state.surface.get());
2546
Dominik Laskowski7e045462018-05-30 13:02:02 -07002547 displayId = state.type;
2548 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002549 producer = bqProducer;
2550 }
2551
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002552 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002553 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002554 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002555 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002556 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002557 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002558 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002559 if (mUseScheduler) {
2560 mScheduler->hotplugReceived(mAppConnectionHandle,
2561 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002562 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002563 } else {
2564 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2565 true);
2566 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002567 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002568 if (mUseScheduler) {
2569 mScheduler->hotplugReceived(mAppConnectionHandle,
2570 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002571 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002572 } else {
2573 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2574 true);
2575 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002576 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002577 }
2578 }
2579 }
2580 }
2581 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002582
2583 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002584}
2585
Mathias Agopian87baae12012-07-31 12:38:26 -07002586void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002587{
Dan Stoza7dde5992015-05-22 09:51:44 -07002588 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002589 mCurrentState.traverseInZOrder([](Layer* layer) {
2590 layer->notifyAvailableFrames();
2591 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002592
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593 /*
2594 * Traversal of the children
2595 * (perform the transaction for each of them if needed)
2596 */
2597
Mathias Agopian3559b072012-08-15 13:46:03 -07002598 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002599 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002601 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602
2603 const uint32_t flags = layer->doTransaction(0);
2604 if (flags & Layer::eVisibleRegion)
2605 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002606 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607 }
2608
2609 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002610 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002611 */
2612
Mathias Agopiane57f2922012-08-09 16:29:12 -07002613 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002614 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002615 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002616 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002617
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002618 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002619 // The transform hint might have changed for some layers
2620 // (either because a display has changed, or because a layer
2621 // as changed).
2622 //
2623 // Walk through all the layers in currentLayers,
2624 // and update their transform hint.
2625 //
2626 // If a layer is visible only on a single display, then that
2627 // display is used to calculate the hint, otherwise we use the
2628 // default display.
2629 //
2630 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2631 // the hint is set before we acquire a buffer from the surface texture.
2632 //
2633 // NOTE: layer transactions have taken place already, so we use their
2634 // drawing state. However, SurfaceFlinger's own transaction has not
2635 // happened yet, so we must use the current state layer list
2636 // (soon to become the drawing state list).
2637 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002638 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002639 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002640 bool first = true;
2641 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002642 // NOTE: we rely on the fact that layers are sorted by
2643 // layerStack first (so we don't have to traverse the list
2644 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002645 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002646 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002647 currentlayerStack = layerStack;
2648 // figure out if this layerstack is mirrored
2649 // (more than one display) if so, pick the default display,
2650 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002651 hintDisplay = nullptr;
2652 for (const auto& [token, display] : mDisplays) {
2653 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2654 if (hintDisplay) {
2655 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002656 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002657 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002658 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002659 }
2660 }
2661 }
2662 }
Chet Haase91d25932013-04-11 15:24:55 -07002663
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002664 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002665 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2666 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002667
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002668 // could be null when this layer is using a layerStack
2669 // that is not visible on any display. Also can occur at
2670 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002671 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002672 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002673
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002674 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002675 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002676 if (hintDisplay) {
2677 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002678 }
Robert Carr2047fae2016-11-28 14:09:09 -08002679
2680 first = false;
2681 });
Mathias Agopian84300952012-11-21 16:02:13 -08002682 }
2683
2684
Mathias Agopian3559b072012-08-15 13:46:03 -07002685 /*
2686 * Perform our own transaction if needed
2687 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002688
2689 if (mLayersAdded) {
2690 mLayersAdded = false;
2691 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002692 mVisibleRegionsDirty = true;
2693 }
2694
2695 // some layers might have been removed, so
2696 // we need to update the regions they're exposing.
2697 if (mLayersRemoved) {
2698 mLayersRemoved = false;
2699 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002700 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002701 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002702 // this layer is not visible anymore
2703 // TODO: we could traverse the tree from front to back and
2704 // compute the actual visible region
2705 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002706 Region visibleReg;
2707 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002708 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002709 }
Robert Carr2047fae2016-11-28 14:09:09 -08002710 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002711 }
2712
2713 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002714
2715 updateCursorAsync();
2716}
2717
2718void SurfaceFlinger::updateCursorAsync()
2719{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002720 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002721 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002722 continue;
2723 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002724
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002725 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2726 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002727 }
2728 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002729}
2730
2731void SurfaceFlinger::commitTransaction()
2732{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002733 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002734 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002735 for (const auto& l : mLayersPendingRemoval) {
2736 recordBufferingStats(l->getName().string(),
2737 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002738
2739 // We need to release the HWC layers when the Layer is removed
2740 // from the current state otherwise the HWC layer just continues
2741 // showing at its last configured state until we eventually
2742 // abandon the buffer queue.
2743 if (l->isRemovedFromCurrentState()) {
2744 l->destroyAllHwcLayers();
2745 l->releasePendingBuffer(systemTime());
2746 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002747 }
2748 mLayersPendingRemoval.clear();
2749 }
2750
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002751 // If this transaction is part of a window animation then the next frame
2752 // we composite should be considered an animation as well.
2753 mAnimCompositionPending = mAnimTransactionPending;
2754
Mathias Agopian4fec8732012-06-29 14:12:52 -07002755 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002756 // clear the "changed" flags in current state
2757 mCurrentState.colorMatrixChanged = false;
2758
Robert Carr1f0a16a2016-10-24 16:27:39 -07002759 mDrawingState.traverseInZOrder([](Layer* layer) {
2760 layer->commitChildList();
2761 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002762 mTransactionPending = false;
2763 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002764 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765}
2766
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002767void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2768 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002769 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002770 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002771
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772 Region aboveOpaqueLayers;
2773 Region aboveCoveredLayers;
2774 Region dirty;
2775
Mathias Agopian87baae12012-07-31 12:38:26 -07002776 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777
Robert Carr2047fae2016-11-28 14:09:09 -08002778 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002780 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781
Jesse Hall01e29052013-02-19 16:13:35 -08002782 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002783 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002784 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002785 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002786
Mathias Agopianab028732010-03-16 16:41:46 -07002787 /*
2788 * opaqueRegion: area of a surface that is fully opaque.
2789 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002791
2792 /*
2793 * visibleRegion: area of a surface that is visible on screen
2794 * and not fully transparent. This is essentially the layer's
2795 * footprint minus the opaque regions above it.
2796 * Areas covered by a translucent surface are considered visible.
2797 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002799
2800 /*
2801 * coveredRegion: area of a surface that is covered by all
2802 * visible regions above it (which includes the translucent areas).
2803 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002804 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002805
Jesse Halla8026d22012-09-25 13:25:04 -07002806 /*
2807 * transparentRegion: area of a surface that is hinted to be completely
2808 * transparent. This is only used to tell when the layer has no visible
2809 * non-transparent regions and can be removed from the layer list. It
2810 * does not affect the visibleRegion of this layer or any layers
2811 * beneath it. The hint may not be correct if apps don't respect the
2812 * SurfaceView restrictions (which, sadly, some don't).
2813 */
2814 Region transparentRegion;
2815
Mathias Agopianab028732010-03-16 16:41:46 -07002816
2817 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002818 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002819 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002820 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002821 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002822 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002823 if (!visibleRegion.isEmpty()) {
2824 // Remove the transparent area from the visible region
2825 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002826 if (tr.preserveRects()) {
2827 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002828 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002829 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002830 // transformation too complex, can't do the
2831 // transparent region optimization.
2832 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002833 }
Mathias Agopianab028732010-03-16 16:41:46 -07002834 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835
Mathias Agopianab028732010-03-16 16:41:46 -07002836 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002837 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002838 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002839 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002840 // the opaque region is the layer's footprint
2841 opaqueRegion = visibleRegion;
2842 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843 }
2844 }
2845
Robert Carre5f4f692018-01-12 13:12:28 -08002846 if (visibleRegion.isEmpty()) {
2847 layer->clearVisibilityRegions();
2848 return;
2849 }
2850
Mathias Agopianab028732010-03-16 16:41:46 -07002851 // Clip the covered region to the visible region
2852 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2853
2854 // Update aboveCoveredLayers for next (lower) layer
2855 aboveCoveredLayers.orSelf(visibleRegion);
2856
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857 // subtract the opaque region covered by the layers above us
2858 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859
2860 // compute this layer's dirty region
2861 if (layer->contentDirty) {
2862 // we need to invalidate the whole region
2863 dirty = visibleRegion;
2864 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002865 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866 layer->contentDirty = false;
2867 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002868 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002869 * the exposed region consists of two components:
2870 * 1) what's VISIBLE now and was COVERED before
2871 * 2) what's EXPOSED now less what was EXPOSED before
2872 *
2873 * note that (1) is conservative, we start with the whole
2874 * visible region but only keep what used to be covered by
2875 * something -- which mean it may have been exposed.
2876 *
2877 * (2) handles areas that were not covered by anything but got
2878 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002879 */
Mathias Agopianab028732010-03-16 16:41:46 -07002880 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002881 const Region oldVisibleRegion = layer->visibleRegion;
2882 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002883 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2884 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885 }
2886 dirty.subtractSelf(aboveOpaqueLayers);
2887
2888 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002889 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890
Mathias Agopianab028732010-03-16 16:41:46 -07002891 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002893
Jesse Halla8026d22012-09-25 13:25:04 -07002894 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895 layer->setVisibleRegion(visibleRegion);
2896 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002897 layer->setVisibleNonTransparentRegion(
2898 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002899 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002900
Mathias Agopian87baae12012-07-31 12:38:26 -07002901 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002902}
2903
Chia-I Wuab0c3192017-08-01 11:29:00 -07002904void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002905 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002906 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2907 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002908 }
2909 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002910}
2911
Dan Stoza6b9454d2014-11-07 16:00:59 -08002912bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002913{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002914 ALOGV("handlePageFlip");
2915
Brian Andersond6927fb2016-07-23 23:37:30 -07002916 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002917
Mathias Agopian4fec8732012-06-29 14:12:52 -07002918 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002919 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002920 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002921
2922 // Store the set of layers that need updates. This set must not change as
2923 // buffers are being latched, as this could result in a deadlock.
2924 // Example: Two producers share the same command stream and:
2925 // 1.) Layer 0 is latched
2926 // 2.) Layer 0 gets a new frame
2927 // 2.) Layer 1 gets a new frame
2928 // 3.) Layer 1 is latched.
2929 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2930 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002931 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002932 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002933 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002934 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2935 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002936 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002937 } else {
2938 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002939 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002940 } else {
2941 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002942 }
Robert Carr2047fae2016-11-28 14:09:09 -08002943 });
2944
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002946 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002947 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002948 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002949 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002950 newDataLatched = true;
2951 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002952 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002953
Alec Mouri86770e52018-09-24 22:40:58 +00002954 // Clear the renderengine fence here...
2955 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2956 // clear instead of sp::clear.
2957 getBE().flushFence = Fence::NO_FENCE;
2958
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002959 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002960
2961 // If we will need to wake up at some time in the future to deal with a
2962 // queued frame that shouldn't be displayed during this vsync period, wake
2963 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002964 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002965 signalLayerUpdate();
2966 }
2967
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002968 // enter boot animation on first buffer latch
2969 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2970 ALOGI("Enter boot animation");
2971 mBootStage = BootStage::BOOTANIMATION;
2972 }
2973
Dan Stoza6b9454d2014-11-07 16:00:59 -08002974 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002975 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002976}
2977
Mathias Agopianad456f92011-01-13 17:53:01 -08002978void SurfaceFlinger::invalidateHwcGeometry()
2979{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002980 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002981}
2982
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002983void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2984 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002985 // We only need to actually compose the display if:
2986 // 1) It is being handled by hardware composer, which may need this to
2987 // keep its virtual display state machine in sync, or
2988 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002989 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002990 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002991 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002992 return;
2993 }
2994
Dan Stoza9e56aa02015-11-02 13:00:03 -08002995 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002996 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002997
2998 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002999 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000}
3001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003002bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003003 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003004
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003005 const Region bounds(display->bounds());
3006 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003007 const auto displayId = display->getId();
3008 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003009 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003010
Peiyong Lind3788632018-09-18 16:01:31 -07003011 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003012 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003013 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003014
Dan Stoza9e56aa02015-11-02 13:00:03 -08003015 if (hasClientComposition) {
3016 ALOGV("hasClientComposition");
3017
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003018 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003019 if (display->hasWideColorGamut()) {
3020 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003021 }
3022 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003023 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003024 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003025
Dominik Laskowski7e045462018-05-30 13:02:02 -07003026 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003027 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3028 HWC2::Capability::SkipClientColorTransform);
3029
Peiyong Lind3788632018-09-18 16:01:31 -07003030 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003031 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3032 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003033 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003034 }
3035
Chia-I Wud49d6692018-06-27 07:17:41 +08003036 // The current enhanced saturation matrix is designed to enhance Display P3,
3037 // thus we only apply this matrix when the render intent is not colorimetric
3038 // and the output color space is Display P3.
3039 needsEnhancedColorMatrix =
3040 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3041 outputDataspace == Dataspace::DISPLAY_P3);
3042 if (needsEnhancedColorMatrix) {
3043 colorMatrix *= mEnhancedSaturationMatrix;
3044 }
3045
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003046 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003047 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003048 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003049 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003050
3051 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003052 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3053 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3054 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003055 }
3056 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003057 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003058
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003059 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003060 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003061 // when using overlays, we assume a fully transparent framebuffer
3062 // NOTE: we could reduce how much we need to clear, for instance
3063 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003064 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003065 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003066 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003067 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003068 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003069 // we're left with the letterbox region
3070 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003071 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003072
3073 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003074 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003075
Mathias Agopianb9494d52012-04-18 02:28:45 -07003076 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003077 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003078 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003079 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003080 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003081 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003082
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003083 const Rect& bounds = display->getBounds();
3084 const Rect& scissor = display->getScissor();
3085 if (scissor != bounds) {
3086 // scissor doesn't match the screen's dimensions, so we
3087 // need to clear everything outside of it and enable
3088 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003089
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003090 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003091 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003092 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003093 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003094
Mathias Agopian85d751c2012-08-29 16:59:24 -07003095 /*
3096 * and then, render the layers targeted at the framebuffer
3097 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003098
Dan Stoza9e56aa02015-11-02 13:00:03 -08003099 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003100 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003101 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003102 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003103 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003104 displayTransform.transform(layer->visibleRegion)));
3105 ALOGV("Layer: %s", layer->getName().string());
3106 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003107 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003108 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003109 case HWC2::Composition::Cursor:
3110 case HWC2::Composition::Device:
3111 case HWC2::Composition::Sideband:
3112 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003113 const Layer::State& state(layer->getDrawingState());
3114 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3115 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3116 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003117 // never clear the very first layer since we're
3118 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003119 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003120 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003121 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003122 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003123 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003124 if (layer->hasColorTransform()) {
3125 mat4 tmpMatrix;
3126 if (applyColorMatrix) {
3127 tmpMatrix = mDrawingState.colorMatrix;
3128 }
3129 tmpMatrix *= layer->getColorTransform();
3130 if (needsEnhancedColorMatrix) {
3131 tmpMatrix *= mEnhancedSaturationMatrix;
3132 }
3133 getRenderEngine().setColorTransform(tmpMatrix);
3134 } else {
3135 getRenderEngine().setColorTransform(colorMatrix);
3136 }
David Sodmanc1498e62018-09-12 14:36:26 -07003137 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003138 break;
3139 }
3140 default:
3141 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003142 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003143 } else {
3144 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003145 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003146 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003147 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003148
Peiyong Lind3788632018-09-18 16:01:31 -07003149 // Clear color transform matrix at the end of the frame.
3150 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003151
Mathias Agopianf45c5102012-10-24 16:29:17 -07003152 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003153 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003154 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155}
3156
Chia-I Wu28e3a252018-09-07 12:05:02 -07003157void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003158 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003159 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160}
3161
Dan Stoza7d89d062015-04-30 13:29:25 -07003162status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003163 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003164 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003165 const sp<Layer>& lbc,
3166 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003167{
Dan Stoza7d89d062015-04-30 13:29:25 -07003168 // add this layer to the current state list
3169 {
3170 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003171 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003172 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3173 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003174 return NO_MEMORY;
3175 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003176 if (parent == nullptr) {
3177 mCurrentState.layersSortedByZ.add(lbc);
3178 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003179 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003180 ALOGE("addClientLayer called with a removed parent");
3181 return NAME_NOT_FOUND;
3182 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003183 parent->addChild(lbc);
3184 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003185
Yiwei Zhang243b3782018-05-15 17:40:04 -07003186 if (gbc != nullptr) {
3187 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3188 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3189 mMaxGraphicBufferProducerListSize,
3190 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3191 mGraphicBufferProducerList.size(),
3192 mMaxGraphicBufferProducerListSize, mNumLayers);
3193 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003194 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003195 }
3196
Mathias Agopian96f08192010-06-02 23:28:45 -07003197 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003198 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003199
Dan Stoza7d89d062015-04-30 13:29:25 -07003200 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003201}
3202
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003203status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003204 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003205 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3206}
Robert Carr7f9b8992017-03-10 11:08:39 -08003207
Robert Carr2e102c92018-10-23 12:11:15 -07003208status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer,
chaviwca27f252018-02-06 16:46:39 -08003209 bool topLevelOnly) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003210 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003211 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003212 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003213 if (topLevelOnly) {
3214 return NO_ERROR;
3215 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003216 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003217 } else {
3218 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003219 }
3220
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003221 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003222
3223 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003224 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225}
3226
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003227uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003228 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003229}
3230
Mathias Agopian3f844832013-08-07 21:24:32 -07003231uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003232 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233}
3234
Mathias Agopian3f844832013-08-07 21:24:32 -07003235uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003236 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003237}
3238
3239uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003240 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003241 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003242 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003243 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003244 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003245 }
3246 return old;
3247}
3248
chaviwca27f252018-02-06 16:46:39 -08003249bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3250 for (const ComposerState& state : states) {
3251 // Here we need to check that the interface we're given is indeed
3252 // one of our own. A malicious client could give us a nullptr
3253 // IInterface, or one of its own or even one of our own but a
3254 // different type. All these situations would cause us to crash.
3255 if (state.client == nullptr) {
3256 return true;
3257 }
3258
3259 sp<IBinder> binder = IInterface::asBinder(state.client);
3260 if (binder == nullptr) {
3261 return true;
3262 }
3263
3264 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3265 return true;
3266 }
3267 }
3268 return false;
3269}
3270
Mathias Agopian8b33f032012-07-24 20:43:54 -07003271void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003272 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003273 const Vector<DisplayState>& displays,
3274 uint32_t flags)
3275{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003276 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003277 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003278 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003279
chaviwca27f252018-02-06 16:46:39 -08003280 if (containsAnyInvalidClientState(states)) {
3281 return;
3282 }
3283
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003284 if (flags & eAnimation) {
3285 // For window updates that are part of an animation we must wait for
3286 // previous animation "frames" to be handled.
3287 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003288 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003289 if (CC_UNLIKELY(err != NO_ERROR)) {
3290 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003291 // caller after a few seconds.
3292 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3293 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003294 mAnimTransactionPending = false;
3295 break;
3296 }
3297 }
3298 }
3299
chaviwca27f252018-02-06 16:46:39 -08003300 for (const DisplayState& display : displays) {
3301 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003302 }
3303
chaviwca27f252018-02-06 16:46:39 -08003304 for (const ComposerState& state : states) {
3305 transactionFlags |= setClientStateLocked(state);
3306 }
3307
3308 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3309 // as destroyed should only occur after setting all other states. This is to allow for a
3310 // child re-parent to happen before marking its original parent as destroyed (which would
3311 // then mark the child as destroyed).
3312 for (const ComposerState& state : states) {
3313 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003314 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003315
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003316 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3317 // anyway. This can be used as a flush mechanism for previous async transactions.
3318 // Empty animation transaction can be used to simulate back-pressure, so also force a
3319 // transaction for empty animation transactions.
3320 if (transactionFlags == 0 &&
3321 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003322 transactionFlags = eTransactionNeeded;
3323 }
3324
Mathias Agopian386aa982011-11-07 21:58:03 -08003325 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003326 if (mInterceptor->isEnabled()) {
3327 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003328 }
Irvel468051e2016-06-13 16:44:44 -07003329
Mathias Agopian386aa982011-11-07 21:58:03 -08003330 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003331 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3332 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003333 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003334
3335 // if this is a synchronous transaction, wait for it to take effect
3336 // before returning.
3337 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003338 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003339 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003340 if (flags & eAnimation) {
3341 mAnimTransactionPending = true;
3342 }
3343 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003344 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3345 if (CC_UNLIKELY(err != NO_ERROR)) {
3346 // just in case something goes wrong in SF, return to the
3347 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003348 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3349 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003350 break;
3351 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003352 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003353 }
3354}
3355
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003356uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3357 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3358 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003359
Mathias Agopiane57f2922012-08-09 16:29:12 -07003360 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003361 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3362
3363 const uint32_t what = s.what;
3364 if (what & DisplayState::eSurfaceChanged) {
3365 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3366 state.surface = s.surface;
3367 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003368 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003369 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003370 if (what & DisplayState::eLayerStackChanged) {
3371 if (state.layerStack != s.layerStack) {
3372 state.layerStack = s.layerStack;
3373 flags |= eDisplayTransactionNeeded;
3374 }
3375 }
3376 if (what & DisplayState::eDisplayProjectionChanged) {
3377 if (state.orientation != s.orientation) {
3378 state.orientation = s.orientation;
3379 flags |= eDisplayTransactionNeeded;
3380 }
3381 if (state.frame != s.frame) {
3382 state.frame = s.frame;
3383 flags |= eDisplayTransactionNeeded;
3384 }
3385 if (state.viewport != s.viewport) {
3386 state.viewport = s.viewport;
3387 flags |= eDisplayTransactionNeeded;
3388 }
3389 }
3390 if (what & DisplayState::eDisplaySizeChanged) {
3391 if (state.width != s.width) {
3392 state.width = s.width;
3393 flags |= eDisplayTransactionNeeded;
3394 }
3395 if (state.height != s.height) {
3396 state.height = s.height;
3397 flags |= eDisplayTransactionNeeded;
3398 }
3399 }
3400
Mathias Agopiane57f2922012-08-09 16:29:12 -07003401 return flags;
3402}
3403
Robert Carrd4ae7f32018-06-07 16:10:57 -07003404bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3405 IPCThreadState* ipc = IPCThreadState::self();
3406 const int pid = ipc->getCallingPid();
3407 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003408 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003409 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003410 return false;
3411 }
3412 return true;
3413}
3414
chaviwca27f252018-02-06 16:46:39 -08003415uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3416 const layer_state_t& s = composerState.state;
3417 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3418
Mathias Agopian13127d82013-03-05 17:47:11 -08003419 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003420 if (layer == nullptr) {
3421 return 0;
3422 }
3423
chaviw8b3871a2017-11-01 17:41:01 -07003424 uint32_t flags = 0;
3425
3426 const uint32_t what = s.what;
3427 bool geometryAppliesWithResize =
3428 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003429
3430 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3431 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003432 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003433 layer->pushPendingState();
3434 }
3435
chaviw8b3871a2017-11-01 17:41:01 -07003436 if (what & layer_state_t::ePositionChanged) {
3437 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3438 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003439 }
chaviw8b3871a2017-11-01 17:41:01 -07003440 }
3441 if (what & layer_state_t::eLayerChanged) {
3442 // NOTE: index needs to be calculated before we update the state
3443 const auto& p = layer->getParent();
3444 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003445 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003446 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003447 mCurrentState.layersSortedByZ.removeAt(idx);
3448 mCurrentState.layersSortedByZ.add(layer);
3449 // we need traversal (state changed)
3450 // AND transaction (list changed)
3451 flags |= eTransactionNeeded|eTraversalNeeded;
3452 }
chaviw8b3871a2017-11-01 17:41:01 -07003453 } else {
3454 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003455 flags |= eTransactionNeeded|eTraversalNeeded;
3456 }
3457 }
chaviw8b3871a2017-11-01 17:41:01 -07003458 }
3459 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003460 // NOTE: index needs to be calculated before we update the state
3461 const auto& p = layer->getParent();
3462 if (p == nullptr) {
3463 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3464 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3465 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 }
3471 } else {
3472 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3473 flags |= eTransactionNeeded|eTraversalNeeded;
3474 }
chaviw8b3871a2017-11-01 17:41:01 -07003475 }
3476 }
3477 if (what & layer_state_t::eSizeChanged) {
3478 if (layer->setSize(s.w, s.h)) {
3479 flags |= eTraversalNeeded;
3480 }
3481 }
3482 if (what & layer_state_t::eAlphaChanged) {
3483 if (layer->setAlpha(s.alpha))
3484 flags |= eTraversalNeeded;
3485 }
3486 if (what & layer_state_t::eColorChanged) {
3487 if (layer->setColor(s.color))
3488 flags |= eTraversalNeeded;
3489 }
Peiyong Lind3788632018-09-18 16:01:31 -07003490 if (what & layer_state_t::eColorTransformChanged) {
3491 if (layer->setColorTransform(s.colorTransform)) {
3492 flags |= eTraversalNeeded;
3493 }
3494 }
chaviw8b3871a2017-11-01 17:41:01 -07003495 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003496 // TODO: b/109894387
3497 //
3498 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3499 // rotation. To see the problem observe that if we have a square parent, and a child
3500 // of the same size, then we rotate the child 45 degrees around it's center, the child
3501 // must now be cropped to a non rectangular 8 sided region.
3502 //
3503 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3504 // private API, and the WindowManager only uses rotation in one case, which is on a top
3505 // level layer in which cropping is not an issue.
3506 //
3507 // However given that abuse of rotation matrices could lead to surfaces extending outside
3508 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3509 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3510 // transformations.
3511 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003512 flags |= eTraversalNeeded;
3513 }
3514 if (what & layer_state_t::eTransparentRegionChanged) {
3515 if (layer->setTransparentRegionHint(s.transparentRegion))
3516 flags |= eTraversalNeeded;
3517 }
3518 if (what & layer_state_t::eFlagsChanged) {
3519 if (layer->setFlags(s.flags, s.mask))
3520 flags |= eTraversalNeeded;
3521 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003522 if (what & layer_state_t::eCropChanged_legacy) {
3523 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003524 flags |= eTraversalNeeded;
3525 }
chaviw8b3871a2017-11-01 17:41:01 -07003526 if (what & layer_state_t::eLayerStackChanged) {
3527 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3528 // We only allow setting layer stacks for top level layers,
3529 // everything else inherits layer stack from its parent.
3530 if (layer->hasParent()) {
3531 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3532 layer->getName().string());
3533 } else if (idx < 0) {
3534 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3535 "that also does not appear in the top level layer list. Something"
3536 " has gone wrong.", layer->getName().string());
3537 } else if (layer->setLayerStack(s.layerStack)) {
3538 mCurrentState.layersSortedByZ.removeAt(idx);
3539 mCurrentState.layersSortedByZ.add(layer);
3540 // we need traversal (state changed)
3541 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003542 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003543 }
3544 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003545 if (what & layer_state_t::eDeferTransaction_legacy) {
3546 if (s.barrierHandle_legacy != nullptr) {
3547 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3548 } else if (s.barrierGbp_legacy != nullptr) {
3549 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003550 if (authenticateSurfaceTextureLocked(gbp)) {
3551 const auto& otherLayer =
3552 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003553 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003554 } else {
3555 ALOGE("Attempt to defer transaction to to an"
3556 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003557 }
3558 }
chaviw8b3871a2017-11-01 17:41:01 -07003559 // We don't trigger a traversal here because if no other state is
3560 // changed, we don't want this to cause any more work
3561 }
3562 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003563 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003564 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003565 if (!hadParent) {
3566 mCurrentState.layersSortedByZ.remove(layer);
3567 }
chaviw8b3871a2017-11-01 17:41:01 -07003568 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003569 }
chaviw8b3871a2017-11-01 17:41:01 -07003570 }
3571 if (what & layer_state_t::eReparentChildren) {
3572 if (layer->reparentChildren(s.reparentHandle)) {
3573 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003574 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003575 }
chaviw8b3871a2017-11-01 17:41:01 -07003576 if (what & layer_state_t::eDetachChildren) {
3577 layer->detachChildren();
3578 }
3579 if (what & layer_state_t::eOverrideScalingModeChanged) {
3580 layer->setOverrideScalingMode(s.overrideScalingMode);
3581 // We don't trigger a traversal here because if no other state is
3582 // changed, we don't want this to cause any more work
3583 }
Marissa Wall61c58622018-07-18 10:12:20 -07003584 if (what & layer_state_t::eTransformChanged) {
3585 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3586 }
3587 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3588 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3589 flags |= eTraversalNeeded;
3590 }
3591 if (what & layer_state_t::eCropChanged) {
3592 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3593 }
3594 if (what & layer_state_t::eBufferChanged) {
3595 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3596 }
3597 if (what & layer_state_t::eAcquireFenceChanged) {
3598 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3599 }
3600 if (what & layer_state_t::eDataspaceChanged) {
3601 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3602 }
3603 if (what & layer_state_t::eHdrMetadataChanged) {
3604 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3605 }
3606 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3607 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3608 }
3609 if (what & layer_state_t::eApiChanged) {
3610 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3611 }
3612 if (what & layer_state_t::eSidebandStreamChanged) {
3613 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3614 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003615 return flags;
3616}
3617
chaviwca27f252018-02-06 16:46:39 -08003618void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3619 const layer_state_t& state = composerState.state;
3620 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3621
3622 sp<Layer> layer(client->getLayerUser(state.surface));
3623 if (layer == nullptr) {
3624 return;
3625 }
3626
chaviwca27f252018-02-06 16:46:39 -08003627 if (state.what & layer_state_t::eDestroySurface) {
3628 removeLayerLocked(mStateLock, layer);
3629 }
3630}
3631
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003632status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003633 const String8& name,
3634 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003635 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003636 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003637 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003638{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003639 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003640 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003641 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003642 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003643 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003644
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003645 status_t result = NO_ERROR;
3646
3647 sp<Layer> layer;
3648
Cody Northropbc755282017-03-31 12:00:08 -06003649 String8 uniqueName = getUniqueLayerName(name);
3650
Mathias Agopian3165cc22012-08-08 19:42:09 -07003651 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003652 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003653 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3654 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003655
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003656 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003657 case ISurfaceComposerClient::eFXSurfaceBufferState:
3658 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3659 break;
chaviw13fdc492017-06-27 12:40:18 -07003660 case ISurfaceComposerClient::eFXSurfaceColor:
3661 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003662 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003663 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003664 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003665 case ISurfaceComposerClient::eFXSurfaceContainer:
3666 result = createContainerLayer(client,
3667 uniqueName, w, h, flags,
3668 handle, &layer);
3669 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003670 default:
3671 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003672 break;
3673 }
3674
Dan Stoza7d89d062015-04-30 13:29:25 -07003675 if (result != NO_ERROR) {
3676 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003677 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003678
Chia-I Wuab0c3192017-08-01 11:29:00 -07003679 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3680 // TODO b/64227542
3681 if (windowType == 441731) {
3682 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3683 layer->setPrimaryDisplayOnly();
3684 }
3685
Albert Chaulk479c60c2017-01-27 14:21:34 -05003686 layer->setInfo(windowType, ownerUid);
3687
Robert Carr1f0a16a2016-10-24 16:27:39 -07003688 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003689 if (result != NO_ERROR) {
3690 return result;
3691 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003692 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003693
3694 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003695 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003696}
3697
Cody Northropbc755282017-03-31 12:00:08 -06003698String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3699{
3700 bool matchFound = true;
3701 uint32_t dupeCounter = 0;
3702
3703 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3704 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3705
Dan Stoza436ccf32018-06-21 12:10:12 -07003706 // Grab the state lock since we're accessing mCurrentState
3707 Mutex::Autolock lock(mStateLock);
3708
Cody Northropbc755282017-03-31 12:00:08 -06003709 // Loop over layers until we're sure there is no matching name
3710 while (matchFound) {
3711 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003712 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003713 if (layer->getName() == uniqueName) {
3714 matchFound = true;
3715 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3716 }
3717 });
3718 }
3719
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003720 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3721 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003722
3723 return uniqueName;
3724}
3725
Marissa Wallfd668622018-05-10 10:21:13 -07003726status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3727 uint32_t w, uint32_t h, uint32_t flags,
3728 PixelFormat& format, sp<IBinder>* handle,
3729 sp<IGraphicBufferProducer>* gbp,
3730 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003731 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003732 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003733 case PIXEL_FORMAT_TRANSPARENT:
3734 case PIXEL_FORMAT_TRANSLUCENT:
3735 format = PIXEL_FORMAT_RGBA_8888;
3736 break;
3737 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003738 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003739 break;
3740 }
3741
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003742 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003743 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003744 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003745 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003746 *handle = layer->getHandle();
3747 *gbp = layer->getProducer();
3748 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003749 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003750
Marissa Wallfd668622018-05-10 10:21:13 -07003751 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003752 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003753}
3754
Marissa Wall61c58622018-07-18 10:12:20 -07003755status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3756 uint32_t w, uint32_t h, uint32_t flags,
3757 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003758 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003759 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003760 *handle = layer->getHandle();
3761 *outLayer = layer;
3762
3763 return NO_ERROR;
3764}
3765
chaviw13fdc492017-06-27 12:40:18 -07003766status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003767 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003768 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003769{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003770 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003771 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003772 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003773}
3774
Robert Carr6b3f6c52018-08-13 13:05:17 -07003775status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3776 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3777 sp<IBinder>* handle, sp<Layer>* outLayer)
3778{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003779 *outLayer =
3780 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003781 *handle = (*outLayer)->getHandle();
3782 return NO_ERROR;
3783}
3784
3785
Mathias Agopianac9fa422013-02-11 16:40:36 -08003786status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003787{
Robert Carr9524cb32017-02-13 11:32:32 -08003788 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003789 status_t err = NO_ERROR;
3790 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003791 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003792 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003793 err = removeLayer(l);
3794 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3795 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003796 }
3797 return err;
3798}
3799
Robert Carr2e102c92018-10-23 12:11:15 -07003800void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3801 mLayersPendingRemoval.add(layer);
3802 mLayersRemoved = true;
3803 setTransactionFlags(eTransactionNeeded);
3804}
3805
3806void SurfaceFlinger::onHandleDestroyed(const sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003807{
Robert Carr2e102c92018-10-23 12:11:15 -07003808 Mutex::Autolock lock(mStateLock);
3809 markLayerPendingRemovalLocked(mStateLock, layer);
Rob Carr4bba3702018-10-08 21:53:30 +00003810}
3811
Mathias Agopianb60314a2012-04-10 22:09:54 -07003812// ---------------------------------------------------------------------------
3813
Andy McFadden13a082e2012-08-24 10:16:42 -07003814void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003815 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3816 if (!displayToken) return;
3817
Jesse Hall01e29052013-02-19 16:13:35 -08003818 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003819 Vector<ComposerState> state;
3820 Vector<DisplayState> displays;
3821 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003822 d.what = DisplayState::eDisplayProjectionChanged |
3823 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003824 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003825 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003826 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003827 d.frame.makeInvalid();
3828 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003829 d.width = 0;
3830 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003831 displays.add(d);
3832 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003833
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003834 const auto display = getDisplayDevice(displayToken);
3835 if (!display) return;
3836
3837 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3838
3839 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003840 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003841 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003842
Brian Andersond0010582017-03-07 13:20:31 -08003843 // Use phase of 0 since phase is not known.
3844 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003845 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3846 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003847}
3848
3849void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003850 // Async since we may be called from the main thread.
3851 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003852}
3853
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003854void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3855 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003856 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003857 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003858
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003859 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003860 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003861 return;
3862 }
3863
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003864 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003865 ALOGW("Trying to set power mode for virtual display");
3866 return;
3867 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003868
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003869 display->setPowerMode(mode);
3870
Lloyd Pique4dccc412018-01-22 17:21:36 -08003871 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003872 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003873 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003874 if (idx < 0) {
3875 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3876 return;
3877 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003878 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003879 }
3880
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003881 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003882 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003883 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003884 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003885 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003886 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003887 if (mUseScheduler) {
3888 mScheduler->onScreenAcquired(mAppConnectionHandle);
3889 } else {
3890 mEventThread->onScreenAcquired();
3891 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003892 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003893 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003894
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003895 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003896 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003897 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003898
3899 struct sched_param param = {0};
3900 param.sched_priority = 1;
3901 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3902 ALOGW("Couldn't set SCHED_FIFO on display on");
3903 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003904 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003905 // Turn off the display
3906 struct sched_param param = {0};
3907 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3908 ALOGW("Couldn't set SCHED_OTHER on display off");
3909 }
3910
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003911 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003912 if (mUseScheduler) {
3913 mScheduler->disableHardwareVsync(true);
3914 } else {
3915 disableHardwareVsync(true); // also cancels any in-progress resync
3916 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003917 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003918 if (mUseScheduler) {
3919 mScheduler->onScreenReleased(mAppConnectionHandle);
3920 } else {
3921 mEventThread->onScreenReleased();
3922 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003923 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003924
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003925 getHwComposer().setPowerMode(type, mode);
3926 mVisibleRegionsDirty = true;
3927 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003928 } else if (mode == HWC_POWER_MODE_DOZE ||
3929 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003930 // Update display while dozing
3931 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003932 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003933 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003934 if (mUseScheduler) {
3935 mScheduler->onScreenAcquired(mAppConnectionHandle);
3936 } else {
3937 mEventThread->onScreenAcquired();
3938 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003939 resyncToHardwareVsync(true);
3940 }
3941 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3942 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003943 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003944 if (mUseScheduler) {
3945 mScheduler->disableHardwareVsync(true);
3946 } else {
3947 disableHardwareVsync(true); // also cancels any in-progress resync
3948 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003949 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003950 if (mUseScheduler) {
3951 mScheduler->onScreenReleased(mAppConnectionHandle);
3952 } else {
3953 mEventThread->onScreenReleased();
3954 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003955 }
3956 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003957 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003958 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003959 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003960 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003961
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003962 if (display->isPrimary()) {
3963 mTimeStats.setPowerMode(mode);
3964 }
3965
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003966 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003967}
3968
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003969void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003970 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003971 const auto display = getDisplayDevice(displayToken);
3972 if (!display) {
3973 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3974 displayToken.get());
3975 } else if (display->isVirtual()) {
3976 ALOGW("Attempt to set power mode %d for virtual display", mode);
3977 } else {
3978 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003979 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003980 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003981}
3982
3983// ---------------------------------------------------------------------------
3984
Lloyd Pique755e3192018-01-31 16:46:15 -08003985status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3986 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003987 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003988
Mathias Agopianbd115332013-04-18 16:41:04 -07003989 IPCThreadState* ipc = IPCThreadState::self();
3990 const int pid = ipc->getCallingPid();
3991 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003992
Mathias Agopianbd115332013-04-18 16:41:04 -07003993 if ((uid != AID_SHELL) &&
3994 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003995 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003996 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003997 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003998 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003999 // (this would indicate SF is stuck, but we want to be able to
4000 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004001 status_t err = mStateLock.timedLock(s2ns(1));
4002 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004003 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004004 result.appendFormat(
4005 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4006 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004007 }
4008
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004009 bool dumpAll = true;
4010 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004011 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004012
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004013 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004014 if ((index < numArgs) &&
4015 (args[index] == String16("--list"))) {
4016 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004017 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004018 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004019 }
4020
4021 if ((index < numArgs) &&
4022 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004023 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004024 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004025 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004026 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004027
4028 if ((index < numArgs) &&
4029 (args[index] == String16("--latency-clear"))) {
4030 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004031 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004032 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004033 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004034
4035 if ((index < numArgs) &&
4036 (args[index] == String16("--dispsync"))) {
4037 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004038 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004039 dumpAll = false;
4040 }
Dan Stozab90cf072015-03-05 11:05:59 -08004041
4042 if ((index < numArgs) &&
4043 (args[index] == String16("--static-screen"))) {
4044 index++;
4045 dumpStaticScreenStats(result);
4046 dumpAll = false;
4047 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004048
4049 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004050 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004051 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004052 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004053 dumpAll = false;
4054 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004055
4056 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4057 index++;
4058 dumpWideColorInfo(result);
4059 dumpAll = false;
4060 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004061
4062 if ((index < numArgs) &&
4063 (args[index] == String16("--enable-layer-stats"))) {
4064 index++;
4065 mLayerStats.enable();
4066 dumpAll = false;
4067 }
4068
4069 if ((index < numArgs) &&
4070 (args[index] == String16("--disable-layer-stats"))) {
4071 index++;
4072 mLayerStats.disable();
4073 dumpAll = false;
4074 }
4075
4076 if ((index < numArgs) &&
4077 (args[index] == String16("--clear-layer-stats"))) {
4078 index++;
4079 mLayerStats.clear();
4080 dumpAll = false;
4081 }
4082
4083 if ((index < numArgs) &&
4084 (args[index] == String16("--dump-layer-stats"))) {
4085 index++;
4086 mLayerStats.dump(result);
4087 dumpAll = false;
4088 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004089
4090 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004091 (args[index] == String16("--frame-composition"))) {
4092 index++;
4093 dumpFrameCompositionInfo(result);
4094 dumpAll = false;
4095 }
4096
4097 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004098 (args[index] == String16("--display-identification"))) {
4099 index++;
4100 dumpDisplayIdentificationData(result);
4101 dumpAll = false;
4102 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004103
4104 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4105 index++;
4106 mTimeStats.parseArgs(asProto, args, index, result);
4107 dumpAll = false;
4108 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004109 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004110
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004111 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004112 if (asProto) {
4113 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4114 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4115 } else {
4116 dumpAllLocked(args, index, result);
4117 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004118 }
4119
Mathias Agopian9795c422009-08-26 16:36:26 -07004120 if (locked) {
4121 mStateLock.unlock();
4122 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004123 }
4124 write(fd, result.string(), result.size());
4125 return NO_ERROR;
4126}
4127
Dan Stozac7014012014-02-14 15:03:43 -08004128void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4129 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004130{
Robert Carr2047fae2016-11-28 14:09:09 -08004131 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004132 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004133 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004134}
4135
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004136void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004137 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004138{
4139 String8 name;
4140 if (index < args.size()) {
4141 name = String8(args[index]);
4142 index++;
4143 }
4144
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004145 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4146 getHwComposer().isConnected(displayId)) {
4147 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4148 const nsecs_t period = activeConfig->getVsyncPeriod();
4149 result.appendFormat("%" PRId64 "\n", period);
4150 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004151
4152 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004153 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004154 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004155 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004156 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004157 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004158 }
Robert Carr2047fae2016-11-28 14:09:09 -08004159 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004160 }
4161}
4162
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004163void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004164 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004165{
4166 String8 name;
4167 if (index < args.size()) {
4168 name = String8(args[index]);
4169 index++;
4170 }
4171
Robert Carr2047fae2016-11-28 14:09:09 -08004172 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004173 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004174 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004175 }
Robert Carr2047fae2016-11-28 14:09:09 -08004176 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004177
Svetoslavd85084b2014-03-20 10:28:31 -07004178 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004179}
4180
Jamie Gennis6547ff42013-07-16 20:12:42 -07004181// This should only be called from the main thread. Otherwise it would need
4182// the lock and should use mCurrentState rather than mDrawingState.
4183void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004184 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004185 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004186 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004187
4188 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4189}
4190
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004191void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004192{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004193 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004194
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004195 if (isLayerTripleBufferingDisabled())
4196 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004197
4198 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004199 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004200 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004201 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004202 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4203 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004204 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004205}
4206
Dan Stozab90cf072015-03-05 11:05:59 -08004207void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4208{
4209 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004210 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4211 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004212 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004213 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004214 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4215 b + 1, bucketTimeSec, percent);
4216 }
David Sodman4a36e932017-11-07 14:29:47 -08004217 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004218 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004219 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004220 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004221 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004222}
4223
Dan Stozae77c7662016-05-13 11:37:28 -07004224void SurfaceFlinger::recordBufferingStats(const char* layerName,
4225 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004226 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4227 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004228 for (const auto& segment : history) {
4229 if (!segment.usedThirdBuffer) {
4230 stats.twoBufferTime += segment.totalTime;
4231 }
4232 if (segment.occupancyAverage < 1.0f) {
4233 stats.doubleBufferedTime += segment.totalTime;
4234 } else if (segment.occupancyAverage < 2.0f) {
4235 stats.tripleBufferedTime += segment.totalTime;
4236 }
4237 ++stats.numSegments;
4238 stats.totalTime += segment.totalTime;
4239 }
4240}
4241
Brian Andersond6927fb2016-07-23 23:37:30 -07004242void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4243 result.appendFormat("Layer frame timestamps:\n");
4244
4245 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4246 const size_t count = currentLayers.size();
4247 for (size_t i=0 ; i<count ; i++) {
4248 currentLayers[i]->dumpFrameEvents(result);
4249 }
4250}
4251
Dan Stozae77c7662016-05-13 11:37:28 -07004252void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4253 result.append("Buffering stats:\n");
4254 result.append(" [Layer name] <Active time> <Two buffer> "
4255 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004256 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004257 typedef std::tuple<std::string, float, float, float> BufferTuple;
4258 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004259 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004260 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004261 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004262 if (stats.numSegments == 0) {
4263 continue;
4264 }
4265 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4266 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4267 stats.totalTime;
4268 float doubleBufferRatio = static_cast<float>(
4269 stats.doubleBufferedTime) / stats.totalTime;
4270 float tripleBufferRatio = static_cast<float>(
4271 stats.tripleBufferedTime) / stats.totalTime;
4272 sorted.insert({activeTime, {name, twoBufferRatio,
4273 doubleBufferRatio, tripleBufferRatio}});
4274 }
4275 for (const auto& sortedPair : sorted) {
4276 float activeTime = sortedPair.first;
4277 const BufferTuple& values = sortedPair.second;
4278 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4279 std::get<0>(values).c_str(), activeTime,
4280 std::get<1>(values), std::get<2>(values),
4281 std::get<3>(values));
4282 }
4283 result.append("\n");
4284}
4285
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004286void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004287 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004288 const int32_t displayId = display->getId();
4289 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4290 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004291 continue;
4292 }
4293
Dominik Laskowski7e045462018-05-30 13:02:02 -07004294 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004295 uint8_t port;
4296 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004297 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004298 result.append("no identification data\n");
4299 continue;
4300 }
4301
4302 if (!isEdid(data)) {
4303 result.append("unknown identification data: ");
4304 for (uint8_t byte : data) {
4305 result.appendFormat("%x ", byte);
4306 }
4307 result.append("\n");
4308 continue;
4309 }
4310
4311 const auto edid = parseEdid(data);
4312 if (!edid) {
4313 result.append("invalid EDID: ");
4314 for (uint8_t byte : data) {
4315 result.appendFormat("%x ", byte);
4316 }
4317 result.append("\n");
4318 continue;
4319 }
4320
4321 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4322 result.append(edid->displayName.data(), edid->displayName.length());
4323 result.append("\"\n");
4324 }
4325 result.append("\n");
4326}
4327
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004328void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004329 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4330 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004331 result.appendFormat("DisplayColorSetting: %s\n",
4332 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004333
4334 // TODO: print out if wide-color mode is active or not
4335
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004336 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004337 const int32_t displayId = display->getId();
4338 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004339 continue;
4340 }
4341
Dominik Laskowski7e045462018-05-30 13:02:02 -07004342 result.appendFormat("Display %d color modes:\n", displayId);
4343 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004344 for (auto&& mode : modes) {
4345 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4346 }
4347
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004348 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004349 result.appendFormat(" Current color mode: %s (%d)\n",
4350 decodeColorMode(currentMode).c_str(), currentMode);
4351 }
4352 result.append("\n");
4353}
4354
David Sodman7e4ae112018-02-09 15:02:28 -08004355void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4356 std::string stringResult;
4357
4358 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004359 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4360 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004361 continue;
4362 }
4363
Dominik Laskowski05275f12018-11-01 15:03:24 -07004364 const auto& compositionInfoList = it->second;
4365 stringResult += base::StringPrintf("%s\n", display->getDebugName().c_str());
David Sodman7e4ae112018-02-09 15:02:28 -08004366 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4367 for (const auto& compositionInfo : compositionInfoList) {
4368 compositionInfo.dump(stringResult, nullptr);
4369 stringResult += base::StringPrintf("\n");
4370 }
4371 }
4372
4373 result.append(stringResult.c_str());
4374}
4375
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004376LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004377 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004378 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4379 const State& state = useDrawing ? mDrawingState : mCurrentState;
4380 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004381 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004382 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004383 });
4384
4385 return layersProto;
4386}
4387
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004388LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004389 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004390
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004391 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004392 resolution->set_w(display.getWidth());
4393 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004394
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004395 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4396 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4397 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004398
Dominik Laskowski7e045462018-05-30 13:02:02 -07004399 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004400 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004401 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004402 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004403 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004404 }
4405 });
4406
4407 return layersProto;
4408}
4409
Mathias Agopian74d211a2013-04-22 16:55:35 +02004410void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4411 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004412{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004413 bool colorize = false;
4414 if (index < args.size()
4415 && (args[index] == String16("--color"))) {
4416 colorize = true;
4417 index++;
4418 }
4419
4420 Colorizer colorizer(colorize);
4421
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004422 // figure out if we're stuck somewhere
4423 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004424 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004425 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4426
4427 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004428 * Dump library configuration.
4429 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004430
4431 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004432 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004433 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004434 appendSfConfigString(result);
4435 appendUiConfigString(result);
4436 appendGuiConfigString(result);
4437 result.append("\n");
4438
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004439 result.append("\nDisplay identification data:\n");
4440 dumpDisplayIdentificationData(result);
4441
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004442 result.append("\nWide-Color information:\n");
4443 dumpWideColorInfo(result);
4444
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004445 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004446 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004447 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004448 result.append(SyncFeatures::getInstance().toString());
4449 result.append("\n");
4450
Andy McFadden41d67d72014-04-25 16:58:34 -07004451 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004452 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004453 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004454
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004455 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4456 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004457 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4458 getHwComposer().isConnected(displayId)) {
4459 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004460 result.appendFormat("Display %d: "
4461 "app phase %" PRId64 " ns, "
4462 "sf phase %" PRId64 " ns, "
4463 "early app phase %" PRId64 " ns, "
4464 "early sf phase %" PRId64 " ns, "
4465 "early app gl phase %" PRId64 " ns, "
4466 "early sf gl phase %" PRId64 " ns, "
4467 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4468 displayId,
4469 vsyncPhaseOffsetNs,
4470 sfVsyncPhaseOffsetNs,
4471 appEarlyOffset,
4472 sfEarlyOffset,
4473 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004474 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004475 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004476 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004477 result.append("\n");
4478
Dan Stozab90cf072015-03-05 11:05:59 -08004479 // Dump static screen stats
4480 result.append("\n");
4481 dumpStaticScreenStats(result);
4482 result.append("\n");
4483
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004484 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4485
Dan Stozae77c7662016-05-13 11:37:28 -07004486 dumpBufferingStats(result);
4487
Andy McFadden4803b742012-09-24 19:07:20 -07004488 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004489 * Dump the visible layer list
4490 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004491 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004492 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004493 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4494 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004495 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004496
Chia-I Wu2f884132018-09-13 15:17:58 -07004497 {
4498 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4499 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4500 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4501 result.append("\n");
4502 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004503
David Sodman7e4ae112018-02-09 15:02:28 -08004504 result.append("\nFrame-Composition information:\n");
4505 dumpFrameCompositionInfo(result);
4506 result.append("\n");
4507
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004508 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004509 * Dump Display state
4510 */
4511
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004512 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004513 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004514 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004515 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004516 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004517 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004518 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004519
4520 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004521 * Dump SurfaceFlinger global state
4522 */
4523
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004524 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004525 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004526 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004527
Mathias Agopian888c8222012-08-04 21:10:38 -07004528 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004529 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004530
David Sodmanbc815282017-11-05 18:57:52 -08004531 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004532
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004533 if (display) {
4534 display->undefinedRegion.dump(result, "undefinedRegion");
4535 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4536 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004537 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004538 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004539 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004540 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004541
4542 if (display) {
4543 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4544 result.appendFormat(" refresh-rate : %f fps\n"
4545 " x-dpi : %f\n"
4546 " y-dpi : %f\n",
4547 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4548 activeConfig->getDpiY());
4549 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004550
Mathias Agopian74d211a2013-04-22 16:55:35 +02004551 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004552 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004553
Ana Krulec98b5b242018-08-10 15:03:23 -07004554 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004555 /*
4556 * VSYNC state
4557 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004558 if (mUseScheduler) {
4559 mScheduler->dump(mAppConnectionHandle, result);
4560 } else {
4561 mEventThread->dump(result);
4562 }
Dan Stozae22aec72016-08-01 13:20:59 -07004563 result.append("\n");
4564
4565 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004566 * Tracing state
4567 */
4568 mTracing.dump(result);
4569 result.append("\n");
4570
4571 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004572 * HWC layer minidump
4573 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004574 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004575 const int32_t displayId = display->getId();
4576 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004577 continue;
4578 }
4579
Dominik Laskowski7e045462018-05-30 13:02:02 -07004580 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004581 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004582 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004583 result.append("\n");
4584 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004585
4586 /*
4587 * Dump HWComposer state
4588 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004589 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004590 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004591 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004592 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004593 result.appendFormat(" h/w composer %s\n",
4594 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004595 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004596
4597 /*
4598 * Dump gralloc state
4599 */
4600 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4601 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004602
4603 /*
4604 * Dump VrFlinger state if in use.
4605 */
4606 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4607 result.append("VrFlinger state:\n");
4608 result.append(mVrFlinger->Dump().c_str());
4609 result.append("\n");
4610 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004611}
4612
Dominik Laskowski7e045462018-05-30 13:02:02 -07004613const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004614 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004615 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004616 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004617 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004618 }
4619 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004620
4621 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4622 static const Vector<sp<Layer>> empty;
4623 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004624}
4625
Keun young Park63f165f2012-08-31 10:53:36 -07004626bool SurfaceFlinger::startDdmConnection()
4627{
4628 void* libddmconnection_dso =
4629 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4630 if (!libddmconnection_dso) {
4631 return false;
4632 }
4633 void (*DdmConnection_start)(const char* name);
4634 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004635 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004636 if (!DdmConnection_start) {
4637 dlclose(libddmconnection_dso);
4638 return false;
4639 }
4640 (*DdmConnection_start)(getServiceName());
4641 return true;
4642}
4643
Chia-I Wu28f320b2018-05-03 11:02:56 -07004644void SurfaceFlinger::updateColorMatrixLocked() {
4645 mat4 colorMatrix;
4646 if (mGlobalSaturationFactor != 1.0f) {
4647 // Rec.709 luma coefficients
4648 float3 luminance{0.213f, 0.715f, 0.072f};
4649 luminance *= 1.0f - mGlobalSaturationFactor;
4650 mat4 saturationMatrix = mat4(
4651 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4652 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4653 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4654 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4655 );
4656 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4657 } else {
4658 colorMatrix = mClientColorMatrix * mDaltonizer();
4659 }
4660
4661 if (mCurrentState.colorMatrix != colorMatrix) {
4662 mCurrentState.colorMatrix = colorMatrix;
4663 mCurrentState.colorMatrixChanged = true;
4664 setTransactionFlags(eTransactionNeeded);
4665 }
4666}
4667
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004668status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004669#pragma clang diagnostic push
4670#pragma clang diagnostic error "-Wswitch-enum"
4671 switch (static_cast<ISurfaceComposerTag>(code)) {
4672 // These methods should at minimum make sure that the client requested
4673 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004674 case BOOT_FINISHED:
4675 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004676 case CREATE_CONNECTION:
4677 case CREATE_DISPLAY:
4678 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004679 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004680 case GET_ACTIVE_COLOR_MODE:
4681 case GET_ANIMATION_FRAME_STATS:
4682 case GET_HDR_CAPABILITIES:
4683 case SET_ACTIVE_CONFIG:
4684 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004685 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004686 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004687 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4688 IPCThreadState* ipc = IPCThreadState::self();
4689 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4690 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004691 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004692 }
Robert Carr1db73f62016-12-21 12:58:51 -08004693 return OK;
4694 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004695 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004696 IPCThreadState* ipc = IPCThreadState::self();
4697 const int pid = ipc->getCallingPid();
4698 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004699 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4700 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004701 return PERMISSION_DENIED;
4702 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004703 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004704 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004705 // Used by apps to hook Choreographer to SurfaceFlinger.
4706 case CREATE_DISPLAY_EVENT_CONNECTION:
4707 // The following calls are currently used by clients that do not
4708 // request necessary permissions. However, they do not expose any secret
4709 // information, so it is OK to pass them.
4710 case AUTHENTICATE_SURFACE:
4711 case GET_ACTIVE_CONFIG:
4712 case GET_BUILT_IN_DISPLAY:
4713 case GET_DISPLAY_COLOR_MODES:
4714 case GET_DISPLAY_CONFIGS:
4715 case GET_DISPLAY_STATS:
4716 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4717 // Calling setTransactionState is safe, because you need to have been
4718 // granted a reference to Client* and Handle* to do anything with it.
4719 case SET_TRANSACTION_STATE:
4720 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004721 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004722 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004723 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004724 return OK;
4725 }
4726 case CAPTURE_LAYERS:
4727 case CAPTURE_SCREEN: {
4728 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004729 IPCThreadState* ipc = IPCThreadState::self();
4730 const int pid = ipc->getCallingPid();
4731 const int uid = ipc->getCallingUid();
4732 if ((uid != AID_GRAPHICS) &&
4733 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4734 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4735 return PERMISSION_DENIED;
4736 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004737 return OK;
4738 }
4739 // The following codes are deprecated and should never be allowed to access SF.
4740 case CONNECT_DISPLAY_UNUSED:
4741 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4742 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4743 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004744 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004745 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004746
4747 // These codes are used for the IBinder protocol to either interrogate the recipient
4748 // side of the transaction for its canonical interface descriptor or to dump its state.
4749 // We let them pass by default.
4750 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4751 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4752 code == IBinder::SYSPROPS_TRANSACTION) {
4753 return OK;
4754 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004755 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004756 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004757 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004758 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4759 return OK;
4760 }
4761 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4762 return PERMISSION_DENIED;
4763#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004764}
4765
Ana Krulec13be8ad2018-08-21 02:43:56 +00004766status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4767 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004768 status_t credentialCheck = CheckTransactCodeCredentials(code);
4769 if (credentialCheck != OK) {
4770 return credentialCheck;
4771 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004772
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004773 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4774 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004775 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004776 IPCThreadState* ipc = IPCThreadState::self();
4777 const int uid = ipc->getCallingUid();
4778 if (CC_UNLIKELY(uid != AID_SYSTEM
4779 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004780 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004781 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004782 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004783 return PERMISSION_DENIED;
4784 }
4785 int n;
4786 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004787 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004788 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004789 return NO_ERROR;
4790 case 1002: // SHOW_UPDATES
4791 n = data.readInt32();
4792 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004793 invalidateHwcGeometry();
4794 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004795 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004796 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004797 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004798 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004799 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004800 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004801 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004802 setTransactionFlags(
4803 eTransactionNeeded|
4804 eDisplayTransactionNeeded|
4805 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004806 return NO_ERROR;
4807 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004808 case 1006:{ // send empty update
4809 signalRefresh();
4810 return NO_ERROR;
4811 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004812 case 1008: // toggle use of hw composer
4813 n = data.readInt32();
4814 mDebugDisableHWC = n ? 1 : 0;
4815 invalidateHwcGeometry();
4816 repaintEverything();
4817 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004818 case 1009: // toggle use of transform hint
4819 n = data.readInt32();
4820 mDebugDisableTransformHint = n ? 1 : 0;
4821 invalidateHwcGeometry();
4822 repaintEverything();
4823 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004824 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004825 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004826 reply->writeInt32(0);
4827 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004828 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004829 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004830 return NO_ERROR;
4831 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004832 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004833 if (!display) {
4834 return NAME_NOT_FOUND;
4835 }
4836
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004837 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004838 return NO_ERROR;
4839 }
4840 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004841 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004842 // daltonize
4843 n = data.readInt32();
4844 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004845 case 1:
4846 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4847 break;
4848 case 2:
4849 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4850 break;
4851 case 3:
4852 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4853 break;
4854 default:
4855 mDaltonizer.setType(ColorBlindnessType::None);
4856 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004857 }
4858 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004859 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004860 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004861 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004862 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004863
4864 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004865 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004866 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004867 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004868 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004869 // apply a color matrix
4870 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004871 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004872 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004873 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004874 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004875 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004876 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004877 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004878 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004879 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004880 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004881
4882 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4883 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004884 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004885 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4886 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4887 }
4888
Chia-I Wu28f320b2018-05-03 11:02:56 -07004889 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004890 return NO_ERROR;
4891 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004892 // This is an experimental interface
4893 // Needs to be shifted to proper binder interface when we productize
4894 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004895 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004896 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004897 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004898 return NO_ERROR;
4899 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004900 case 1017: {
4901 n = data.readInt32();
4902 mForceFullDamage = static_cast<bool>(n);
4903 return NO_ERROR;
4904 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004905 case 1018: { // Modify Choreographer's phase offset
4906 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004907 if (mUseScheduler) {
4908 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4909 } else {
4910 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4911 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004912 return NO_ERROR;
4913 }
4914 case 1019: { // Modify SurfaceFlinger's phase offset
4915 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004916 if (mUseScheduler) {
4917 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4918 } else {
4919 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4920 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004921 return NO_ERROR;
4922 }
Irvel468051e2016-06-13 16:44:44 -07004923 case 1020: { // Layer updates interceptor
4924 n = data.readInt32();
4925 if (n) {
4926 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004927 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004928 }
4929 else{
4930 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004931 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004932 }
4933 return NO_ERROR;
4934 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004935 case 1021: { // Disable HWC virtual displays
4936 n = data.readInt32();
4937 mUseHwcVirtualDisplays = !n;
4938 return NO_ERROR;
4939 }
Romain Guy0147a172017-06-01 13:53:56 -07004940 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004941 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004942 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004943
Chia-I Wu28f320b2018-05-03 11:02:56 -07004944 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004945 return NO_ERROR;
4946 }
Romain Guy54f154a2017-10-24 21:40:32 +01004947 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004948 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004949 invalidateHwcGeometry();
4950 repaintEverything();
4951 return NO_ERROR;
4952 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004953 // Deprecate, use 1030 to check whether the device is color managed.
4954 case 1024: {
4955 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004956 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004957 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004958 n = data.readInt32();
4959 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004960 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004961 mTracing.enable();
4962 doTracing("tracing.enable");
4963 reply->writeInt32(NO_ERROR);
4964 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004965 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004966 status_t err = mTracing.disable();
4967 reply->writeInt32(err);
4968 }
4969 return NO_ERROR;
4970 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004971 case 1026: { // Get layer tracing status
4972 reply->writeBool(mTracing.isEnabled());
4973 return NO_ERROR;
4974 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004975 // Is a DisplayColorSetting supported?
4976 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004977 const auto display = getDefaultDisplayDevice();
4978 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004979 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004980 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004981
4982 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4983 switch (setting) {
4984 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004985 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004986 break;
4987 case DisplayColorSetting::UNMANAGED:
4988 reply->writeBool(true);
4989 break;
4990 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004991 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004992 break;
4993 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004994 reply->writeBool(
4995 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004996 break;
4997 }
4998 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004999 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005000 // Is VrFlinger active?
5001 case 1028: {
5002 Mutex::Autolock _l(mStateLock);
5003 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5004 return NO_ERROR;
5005 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005006 // Is device color managed?
5007 case 1030: {
5008 reply->writeBool(useColorManagement);
5009 return NO_ERROR;
5010 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005011 // Override default composition data space
5012 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5013 // && adb shell stop zygote && adb shell start zygote
5014 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5015 // adb shell stop zygote && adb shell start zygote
5016 case 1031: {
5017 Mutex::Autolock _l(mStateLock);
5018 n = data.readInt32();
5019 if (n) {
5020 n = data.readInt32();
5021 if (n) {
5022 Dataspace dataspace = static_cast<Dataspace>(n);
5023 if (!validateCompositionDataspace(dataspace)) {
5024 return BAD_VALUE;
5025 }
5026 mDefaultCompositionDataspace = dataspace;
5027 }
5028 n = data.readInt32();
5029 if (n) {
5030 Dataspace dataspace = static_cast<Dataspace>(n);
5031 if (!validateCompositionDataspace(dataspace)) {
5032 return BAD_VALUE;
5033 }
5034 mWideColorGamutCompositionDataspace = dataspace;
5035 }
5036 } else {
5037 // restore composition data space.
5038 mDefaultCompositionDataspace = defaultCompositionDataspace;
5039 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5040 }
5041 return NO_ERROR;
5042 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005043 }
5044 }
5045 return err;
5046}
5047
Steven Thomas6d8110b2017-08-31 18:24:21 -07005048void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005049 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005050 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005051}
5052
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005053// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5054class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005055public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005056 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5057 ~WindowDisconnector() {
5058 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005059 }
5060
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005061private:
5062 ANativeWindow* mWindow;
5063 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005064};
5065
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005066status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005067 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5068 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005069 uint32_t reqWidth, uint32_t reqHeight,
5070 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005071 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005072 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005073
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005074 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005075
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005076 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5077
Chia-I Wu20261cb2018-08-23 12:55:44 -07005078 sp<DisplayDevice> display;
5079 {
5080 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005081
Chia-I Wu20261cb2018-08-23 12:55:44 -07005082 display = getDisplayDeviceLocked(displayToken);
5083 if (!display) return BAD_VALUE;
5084
Chia-I Wucb023152018-08-28 12:57:23 -07005085 // set the requested width/height to the logical display viewport size
5086 // by default
5087 if (reqWidth == 0 || reqHeight == 0) {
5088 reqWidth = uint32_t(display->getViewport().width());
5089 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005090 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005091 }
5092
Peiyong Lin0e003c92018-09-17 11:09:51 -07005093 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5094 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005095
5096 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005097 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005098 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5099 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005100}
5101
5102status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005103 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5104 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005105 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005106 ATRACE_CALL();
5107
5108 class LayerRenderArea : public RenderArea {
5109 public:
Robert Carr578038f2018-03-09 12:25:24 -08005110 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005111 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5112 bool childrenOnly)
5113 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005114 mLayer(layer),
5115 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005116 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005117 mFlinger(flinger),
5118 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005119 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005120 Rect getBounds() const override {
5121 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005122 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005123 }
Marissa Wall61c58622018-07-18 10:12:20 -07005124 int getHeight() const override {
5125 return mLayer->getActiveHeight(mLayer->getDrawingState());
5126 }
5127 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005128 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005129 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005130 Rect getSourceCrop() const override {
5131 if (mCrop.isEmpty()) {
5132 return getBounds();
5133 } else {
5134 return mCrop;
5135 }
5136 }
Robert Carr578038f2018-03-09 12:25:24 -08005137 class ReparentForDrawing {
5138 public:
5139 const sp<Layer>& oldParent;
5140 const sp<Layer>& newParent;
5141
5142 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5143 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005144 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005145 }
Robert Carr15eae092018-03-23 13:43:53 -07005146 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005147 };
5148
5149 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005150 const Rect sourceCrop = getSourceCrop();
5151 // no need to check rotation because there is none
5152 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5153 sourceCrop.height() != getReqHeight();
5154
Robert Carr578038f2018-03-09 12:25:24 -08005155 if (!mChildrenOnly) {
5156 mTransform = mLayer->getTransform().inverse();
5157 drawLayers();
5158 } else {
5159 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005160 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005161 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5162 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005163
5164 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5165 drawLayers();
5166 }
5167 }
chaviwa76b2712017-09-20 12:02:26 -07005168
chaviwa76b2712017-09-20 12:02:26 -07005169 private:
chaviw7206d492017-11-10 16:16:12 -08005170 const sp<Layer> mLayer;
5171 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005172
5173 // In the "childrenOnly" case we reparent the children to a screenshot
5174 // layer which has no properties set and which does not draw.
5175 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005176 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005177 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005178
5179 SurfaceFlinger* mFlinger;
5180 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005181 };
5182
5183 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5184 auto parent = layerHandle->owner.promote();
5185
Robert Carr2e102c92018-10-23 12:11:15 -07005186 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005187 ALOGE("captureLayers called with a removed parent");
5188 return NAME_NOT_FOUND;
5189 }
5190
Robert Carr578038f2018-03-09 12:25:24 -08005191 const int uid = IPCThreadState::self()->getCallingUid();
5192 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5193 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5194 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5195 return PERMISSION_DENIED;
5196 }
5197
chaviw7206d492017-11-10 16:16:12 -08005198 Rect crop(sourceCrop);
5199 if (sourceCrop.width() <= 0) {
5200 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005201 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005202 }
5203
5204 if (sourceCrop.height() <= 0) {
5205 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005206 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005207 }
5208
5209 int32_t reqWidth = crop.width() * frameScale;
5210 int32_t reqHeight = crop.height() * frameScale;
5211
Chia-I Wu20261cb2018-08-23 12:55:44 -07005212 // really small crop or frameScale
5213 if (reqWidth <= 0) {
5214 reqWidth = 1;
5215 }
5216 if (reqHeight <= 0) {
5217 reqHeight = 1;
5218 }
5219
Peiyong Lin0e003c92018-09-17 11:09:51 -07005220 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005221
Robert Carr578038f2018-03-09 12:25:24 -08005222 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005223 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5224 if (!layer->isVisible()) {
5225 return;
Robert Carr578038f2018-03-09 12:25:24 -08005226 } else if (childrenOnly && layer == parent.get()) {
5227 return;
chaviwa76b2712017-09-20 12:02:26 -07005228 }
5229 visitor(layer);
5230 });
5231 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005232 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005233}
5234
5235status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5236 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005237 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005238 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005239 bool useIdentityTransform) {
5240 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005241
Peiyong Lin0e003c92018-09-17 11:09:51 -07005242 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005243 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5244 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005245 *outBuffer =
5246 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5247 static_cast<android_pixel_format>(reqPixelFormat), 1,
5248 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005249
5250 // This mutex protects syncFd and captureResult for communication of the return values from the
5251 // main thread back to this Binder thread
5252 std::mutex captureMutex;
5253 std::condition_variable captureCondition;
5254 std::unique_lock<std::mutex> captureLock(captureMutex);
5255 int syncFd = -1;
5256 std::optional<status_t> captureResult;
5257
Robert Carr03480e22018-01-04 16:02:06 -08005258 const int uid = IPCThreadState::self()->getCallingUid();
5259 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5260
Dominik Laskowski8c001672018-05-30 16:52:06 -07005261 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005262 // If there is a refresh pending, bug out early and tell the binder thread to try again
5263 // after the refresh.
5264 if (mRefreshPending) {
5265 ATRACE_NAME("Skipping screenshot for now");
5266 std::unique_lock<std::mutex> captureLock(captureMutex);
5267 captureResult = std::make_optional<status_t>(EAGAIN);
5268 captureCondition.notify_one();
5269 return;
5270 }
5271
5272 status_t result = NO_ERROR;
5273 int fd = -1;
5274 {
5275 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005276 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005277 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5278 useIdentityTransform, forSystem, &fd);
5279 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005280 }
5281
5282 {
5283 std::unique_lock<std::mutex> captureLock(captureMutex);
5284 syncFd = fd;
5285 captureResult = std::make_optional<status_t>(result);
5286 captureCondition.notify_one();
5287 }
5288 });
5289
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005290 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005291 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005292 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005293 while (*captureResult == EAGAIN) {
5294 captureResult.reset();
5295 result = postMessageAsync(message);
5296 if (result != NO_ERROR) {
5297 return result;
5298 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005299 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005300 }
5301 result = *captureResult;
5302 }
5303
5304 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005305 sync_wait(syncFd, -1);
5306 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005307 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005308
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005309 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005310}
5311
chaviwa76b2712017-09-20 12:02:26 -07005312void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005313 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005314 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005315 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005316
Lloyd Pique144e1162017-12-20 16:44:52 -08005317 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005318
chaviwa76b2712017-09-20 12:02:26 -07005319 const auto reqWidth = renderArea.getReqWidth();
5320 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005321 const auto sourceCrop = renderArea.getSourceCrop();
5322 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005323
Peiyong Lin0e003c92018-09-17 11:09:51 -07005324 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005325 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005326
Mathias Agopian180f10d2013-04-10 22:55:41 -07005327 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005328 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005329
5330 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005331 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005332 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005333
chaviw50da5042018-04-09 13:49:37 -07005334 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005335 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005336 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005337
chaviwa76b2712017-09-20 12:02:26 -07005338 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005339 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005340 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005341 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005342 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005343}
5344
chaviwa76b2712017-09-20 12:02:26 -07005345status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5346 TraverseLayersFunction traverseLayers,
5347 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005348 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005349 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005350 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005351 ATRACE_CALL();
5352
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005353 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005354
5355 traverseLayers([&](Layer* layer) {
5356 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5357 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005358
Robert Carr03480e22018-01-04 16:02:06 -08005359 // We allow the system server to take screenshots of secure layers for
5360 // use in situations like the Screen-rotation animation and place
5361 // the impetus on WindowManager to not persist them.
5362 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005363 ALOGW("FB is protected: PERMISSION_DENIED");
5364 return PERMISSION_DENIED;
5365 }
5366
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005367 // this binds the given EGLImage as a framebuffer for the
5368 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005369 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005370 if (bufferBond.getStatus() != NO_ERROR) {
5371 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005372 return INVALID_OPERATION;
5373 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005374
Dan Stozaabcda352017-06-01 14:37:39 -07005375 // this will in fact render into our dequeued buffer
5376 // via an FBO, which means we didn't have to create
5377 // an EGLSurface and therefore we're not
5378 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005379 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005380
Alec Mouri492bc572018-09-11 21:40:04 +00005381 base::unique_fd syncFd = getRenderEngine().flush();
5382 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005383 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005384 }
Alec Mouri492bc572018-09-11 21:40:04 +00005385 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005386
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005387 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005388}
5389
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005390// ---------------------------------------------------------------------------
5391
Dan Stoza412903f2017-04-27 13:42:17 -07005392void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5393 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005394}
5395
Dan Stoza412903f2017-04-27 13:42:17 -07005396void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5397 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005398}
5399
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005400void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005401 const LayerVector::Visitor& visitor) {
5402 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005403 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005404 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005405 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005406 continue;
5407 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005408 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005409 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005410 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005411 return;
5412 }
chaviwa76b2712017-09-20 12:02:26 -07005413 if (!layer->isVisible()) {
5414 return;
5415 }
5416 visitor(layer);
5417 });
5418 }
5419}
5420
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005421}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005422
Lloyd Pique074e8122018-07-26 12:57:23 -07005423
Mathias Agopian3f844832013-08-07 21:24:32 -07005424#if defined(__gl_h_)
5425#error "don't include gl/gl.h in this file"
5426#endif
5427
5428#if defined(__gl2_h_)
5429#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005430#endif