blob: 91673992167b0c7421b6600f2636872436fcde7f [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>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#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"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080067#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080070#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070071#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080072#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070073#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080074#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070076#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Steven Thomasb02664d2017-07-26 18:48:28 -070081#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070082#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070083#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070084#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070085#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include "Effects/Daltonizer.h"
88
Mathias Agopian875d8e12013-06-07 15:35:48 -070089#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070090#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070091
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080093#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
94#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090095#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090096
chaviw1d044282017-09-27 12:19:28 -070097#include <layerproto/LayerProtoParser.h>
98
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099#define DISPLAY_COUNT 1
100
Mathias Agopianfee2b462013-07-03 12:34:01 -0700101/*
102 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
103 * black pixels.
104 */
105#define DEBUG_SCREENSHOTS false
106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108
Jaesoo Lee43518572017-01-23 19:03:16 +0900109using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700111using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700112using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700113using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700114using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
Steven Thomasb02664d2017-07-26 18:48:28 -0700116namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700117
118#pragma clang diagnostic push
119#pragma clang diagnostic error "-Wswitch-enum"
120
121bool isWideColorMode(const ColorMode colorMode) {
122 switch (colorMode) {
123 case ColorMode::DISPLAY_P3:
124 case ColorMode::ADOBE_RGB:
125 case ColorMode::DCI_P3:
126 case ColorMode::BT2020:
127 case ColorMode::BT2100_PQ:
128 case ColorMode::BT2100_HLG:
129 return true;
130 case ColorMode::NATIVE:
131 case ColorMode::STANDARD_BT601_625:
132 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
133 case ColorMode::STANDARD_BT601_525:
134 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
135 case ColorMode::STANDARD_BT709:
136 case ColorMode::SRGB:
137 return false;
138 }
139 return false;
140}
141
142#pragma clang diagnostic pop
143
Steven Thomasb02664d2017-07-26 18:48:28 -0700144class ConditionalLock {
145public:
146 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
147 if (lock) {
148 mMutex.lock();
149 }
150 }
151 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
152private:
153 Mutex& mMutex;
154 bool mLocked;
155};
Peiyong Linfca547f2018-07-09 13:03:33 -0700156
Steven Thomasb02664d2017-07-26 18:48:28 -0700157} // namespace anonymous
158
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159// ---------------------------------------------------------------------------
160
Mathias Agopian99b49842011-06-27 16:05:52 -0700161const String16 sHardwareTest("android.permission.HARDWARE_TEST");
162const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
163const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
164const String16 sDump("android.permission.DUMP");
165
166// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800167int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
168int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700169int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700170bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800171uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800172bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800173bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800174int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800175// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600176bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700177
Kalle Raitaa099a242017-01-11 11:17:29 -0800178
179std::string getHwcServiceName() {
180 char value[PROPERTY_VALUE_MAX] = {};
181 property_get("debug.sf.hwc_service_name", value, "default");
182 ALOGI("Using HWComposer service: '%s'", value);
183 return std::string(value);
184}
185
186bool useTrebleTestingOverride() {
187 char value[PROPERTY_VALUE_MAX] = {};
188 property_get("debug.sf.treble_testing_override", value, "false");
189 ALOGI("Treble testing override: '%s'", value);
190 return std::string(value) == "true";
191}
192
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800193std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
194 switch(displayColorSetting) {
195 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700196 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800197 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700198 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800199 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700200 return std::string("Enhanced");
201 default:
202 return std::string("Unknown ") +
203 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800204 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800205}
206
Lloyd Pique99d3da52018-01-22 17:48:03 -0800207NativeWindowSurface::~NativeWindowSurface() = default;
208
209namespace impl {
210
211class NativeWindowSurface final : public android::NativeWindowSurface {
212public:
213 static std::unique_ptr<android::NativeWindowSurface> create(
214 const sp<IGraphicBufferProducer>& producer) {
215 return std::make_unique<NativeWindowSurface>(producer);
216 }
217
218 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
219 : surface(new Surface(producer, false)) {}
220
221 ~NativeWindowSurface() override = default;
222
223private:
224 sp<ANativeWindow> getNativeWindow() const override { return surface; }
225
226 void preallocateBuffers() override { surface->allocateBuffers(); }
227
228 sp<Surface> surface;
229};
230
231} // namespace impl
232
David Sodmanbc815282017-11-05 18:57:52 -0800233SurfaceFlingerBE::SurfaceFlingerBE()
234 : mHwcServiceName(getHwcServiceName()),
235 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800236 mFrameBuckets(),
237 mTotalTime(0),
238 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800239 mComposerSequenceId(0) {
240}
241
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800242SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800243 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700245 mTransactionPending(false),
246 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700247 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700248 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700249 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800250 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700251 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800253 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800254 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800255 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700257 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700258 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700259 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700260 mDebugInSwapBuffers(0),
261 mLastSwapBufferTime(0),
262 mDebugInTransaction(0),
263 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700264 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000265 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700266 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700267 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800268 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800269 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700270 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800271 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800272 mCreateBufferQueue(&BufferQueue::createBufferQueue),
273 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800274
275SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(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);
305
Iris Chang7501ed62018-04-30 14:45:42 +0800306 V1_1::DisplayOrientation primaryDisplayOrientation =
307 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
308 V1_1::DisplayOrientation::ORIENTATION_0);
309
310 switch (primaryDisplayOrientation) {
311 case V1_1::DisplayOrientation::ORIENTATION_90:
312 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
313 break;
314 case V1_1::DisplayOrientation::ORIENTATION_180:
315 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
316 break;
317 case V1_1::DisplayOrientation::ORIENTATION_270:
318 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
319 break;
320 default:
321 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
322 break;
323 }
324 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
325
David Sodman99974d22017-11-28 12:04:33 -0800326 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700327
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800328 // debugging stuff...
329 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700330
Mathias Agopianb4b17302013-03-20 18:36:41 -0700331 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700332 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800334 property_get("debug.sf.showupdates", value, "0");
335 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700336
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700337 property_get("debug.sf.ddms", value, "0");
338 mDebugDDMS = atoi(value);
339 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700340 if (!startDdmConnection()) {
341 // start failed, and DDMS debugging not enabled
342 mDebugDDMS = 0;
343 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700344 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700345 ALOGI_IF(mDebugRegion, "showupdates enabled");
346 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700347
348 property_get("debug.sf.disable_backpressure", value, "0");
349 mPropagateBackpressure = !atoi(value);
350 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700351
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800352 property_get("debug.sf.enable_hwc_vds", value, "0");
353 mUseHwcVirtualDisplays = atoi(value);
354 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800355
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800356 property_get("ro.sf.disable_triple_buffer", value, "1");
357 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800358 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700359
Yiwei Zhang243b3782018-05-15 17:40:04 -0700360 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700361 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
362 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
363
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200364 property_get("debug.sf.early_phase_offset_ns", value, "-1");
365 const int earlySfOffsetNs = atoi(value);
366
367 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
368 const int earlyGlSfOffsetNs = atoi(value);
369
370 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
371 const int earlyAppOffsetNs = atoi(value);
372
373 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
374 const int earlyGlAppOffsetNs = atoi(value);
375
376 const VSyncModulator::Offsets earlyOffsets =
377 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
378 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
379 const VSyncModulator::Offsets earlyGlOffsets =
380 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
381 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
382 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
383 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700384
Romain Guy11d63f42017-07-20 12:47:14 -0700385 // We should be reading 'persist.sys.sf.color_saturation' here
386 // but since /data may be encrypted, we need to wait until after vold
387 // comes online to attempt to read the property. The property is
388 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800389
390 if (useTrebleTestingOverride()) {
391 // Without the override SurfaceFlinger cannot connect to HIDL
392 // services that are not listed in the manifests. Considered
393 // deriving the setting from the set service name, but it
394 // would be brittle if the name that's not 'default' is used
395 // for production purposes later on.
396 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
397 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800398}
399
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800400void SurfaceFlinger::onFirstRef()
401{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800402 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800403}
404
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405SurfaceFlinger::~SurfaceFlinger()
406{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800407}
408
Dan Stozac7014012014-02-14 15:03:43 -0800409void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410{
411 // the window manager died on us. prepare its eulogy.
412
Andy McFadden13a082e2012-08-24 10:16:42 -0700413 // restore initial conditions (default device unblank, etc)
414 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800415
416 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700417 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418}
419
Robert Carr1db73f62016-12-21 12:58:51 -0800420static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700421 status_t err = client->initCheck();
422 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800423 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424 }
Robert Carr1db73f62016-12-21 12:58:51 -0800425 return nullptr;
426}
427
428sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
429 return initClient(new Client(this));
430}
431
432sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
433 const sp<IGraphicBufferProducer>& gbp) {
434 if (authenticateSurfaceTexture(gbp) == false) {
435 return nullptr;
436 }
437 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
438 if (layer == nullptr) {
439 return nullptr;
440 }
441
442 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800443}
444
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700445sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
446 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700447{
448 class DisplayToken : public BBinder {
449 sp<SurfaceFlinger> flinger;
450 virtual ~DisplayToken() {
451 // no more references, this display must be terminated
452 Mutex::Autolock _l(flinger->mStateLock);
453 flinger->mCurrentState.displays.removeItem(this);
454 flinger->setTransactionFlags(eDisplayTransactionNeeded);
455 }
456 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700457 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700458 : flinger(flinger) {
459 }
460 };
461
462 sp<BBinder> token = new DisplayToken(this);
463
464 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700465 DisplayDeviceState info;
466 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700467 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700468 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700469 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800470 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700471 return token;
472}
473
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700474void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700475 Mutex::Autolock _l(mStateLock);
476
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700477 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700478 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700479 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700480 return;
481 }
482
483 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700484 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700485 ALOGE("destroyDisplay called for non-virtual display");
486 return;
487 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700488 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 mCurrentState.displays.removeItemsAt(idx);
490 setTransactionFlags(eDisplayTransactionNeeded);
491}
492
Mathias Agopiane57f2922012-08-09 16:29:12 -0700493sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700494 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800496 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700498 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499}
500
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800501void SurfaceFlinger::bootFinished()
502{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700503 if (mStartPropertySetThread->join() != NO_ERROR) {
504 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800505 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800506 const nsecs_t now = systemTime();
507 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000508 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700509
510 // wait patiently for the window manager death
511 const String16 name("window");
512 sp<IBinder> window(defaultServiceManager()->getService(name));
513 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700514 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700515 }
516
Steven Thomas050b2c82017-03-06 11:45:16 -0800517 if (mVrFlinger) {
518 mVrFlinger->OnBootFinished();
519 }
520
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700521 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700522 // formerly we would just kill the process, but we now ask it to exit so it
523 // can choose where to stop the animation.
524 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700525
526 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
527 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
528 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700529
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800530 postMessageAsync(new LambdaMessage([this] {
531 readPersistentProperties();
532 mBootStage = BootStage::FINISHED;
533 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534}
535
Dan Stoza436ccf32018-06-21 12:10:12 -0700536uint32_t SurfaceFlinger::getNewTexture() {
537 {
538 std::lock_guard lock(mTexturePoolMutex);
539 if (!mTexturePool.empty()) {
540 uint32_t name = mTexturePool.back();
541 mTexturePool.pop_back();
542 ATRACE_INT("TexturePoolSize", mTexturePool.size());
543 return name;
544 }
545
546 // The pool was too small, so increase it for the future
547 ++mTexturePoolSize;
548 }
549
550 // The pool was empty, so we need to get a new texture name directly using a
551 // blocking call to the main thread
552 uint32_t name = 0;
553 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
554 return name;
555}
556
Mathias Agopian3f844832013-08-07 21:24:32 -0700557void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700558 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700559}
560
Lloyd Piquee83f9312018-02-01 12:53:17 -0800561class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700562public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700563 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000564 const char* name) :
565 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700566 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700567 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000568 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
569 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700570 mDispSync(dispSync),
571 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700572 mVsyncMutex(),
573 mPhaseOffset(phaseOffset),
574 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700575
Lloyd Piquee83f9312018-02-01 12:53:17 -0800576 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577
Lloyd Piquee83f9312018-02-01 12:53:17 -0800578 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700579 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700580 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000581 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700582 static_cast<DispSync::Callback*>(this));
583 if (err != NO_ERROR) {
584 ALOGE("error registering vsync callback: %s (%d)",
585 strerror(-err), err);
586 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700587 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588 } else {
589 status_t err = mDispSync->removeEventListener(
590 static_cast<DispSync::Callback*>(this));
591 if (err != NO_ERROR) {
592 ALOGE("error unregistering vsync callback: %s (%d)",
593 strerror(-err), err);
594 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700595 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700596 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700597 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700598 }
599
Lloyd Piquee83f9312018-02-01 12:53:17 -0800600 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700601 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602 mCallback = callback;
603 }
604
Lloyd Piquee83f9312018-02-01 12:53:17 -0800605 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700606 Mutex::Autolock lock(mVsyncMutex);
607
608 // Normalize phaseOffset to [0, period)
609 auto period = mDispSync->getPeriod();
610 phaseOffset %= period;
611 if (phaseOffset < 0) {
612 // If we're here, then phaseOffset is in (-period, 0). After this
613 // operation, it will be in (0, period)
614 phaseOffset += period;
615 }
616 mPhaseOffset = phaseOffset;
617
618 // If we're not enabled, we don't need to mess with the listeners
619 if (!mEnabled) {
620 return;
621 }
622
Dan Stoza84d619e2018-03-28 17:07:36 -0700623 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
624 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700625 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700626 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700627 strerror(-err), err);
628 }
629 }
630
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700631private:
632 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800633 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700634 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700635 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700636 callback = mCallback;
637
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700638 if (mTraceVsync) {
639 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700640 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700641 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700642 }
643
Peiyong Lin566a3b42018-01-09 18:22:43 -0800644 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700645 callback->onVSyncEvent(when);
646 }
647 }
648
Tim Murray4a4e4a22016-04-19 16:29:23 +0000649 const char* const mName;
650
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700651 int mValue;
652
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700653 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700654 const String8 mVsyncOnLabel;
655 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700656
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700657 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700658
659 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800660 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700661
662 Mutex mVsyncMutex; // Protects the following
663 nsecs_t mPhaseOffset;
664 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700665};
666
Lloyd Piquee83f9312018-02-01 12:53:17 -0800667class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700668public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800669 InjectVSyncSource() = default;
670 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700671
Lloyd Piquee83f9312018-02-01 12:53:17 -0800672 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700673 std::lock_guard<std::mutex> lock(mCallbackMutex);
674 mCallback = callback;
675 }
676
Lloyd Piquee83f9312018-02-01 12:53:17 -0800677 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700678 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700679 if (mCallback) {
680 mCallback->onVSyncEvent(when);
681 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700682 }
683
Lloyd Piquee83f9312018-02-01 12:53:17 -0800684 void setVSyncEnabled(bool) override {}
685 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700686
687private:
688 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800689 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700690};
691
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692// Do not call property_set on main thread which will be blocked by init
693// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700694void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700695 ALOGI( "SurfaceFlinger's main thread ready to run. "
696 "Initializing graphics H/W...");
697
Thierry Strudel2924d012017-08-14 15:19:37 -0700698 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900699
Steven Thomasb02664d2017-07-26 18:48:28 -0700700 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800701
Steven Thomasb02664d2017-07-26 18:48:28 -0700702 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800703 mEventThreadSource =
704 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
705 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800706 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700707 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800708 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800709 "appEventThread");
710 mSfEventThreadSource =
711 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
712 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800713
Lloyd Pique24b0a482018-03-09 18:52:26 -0800714 mSFEventThread =
715 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700716 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800717 [this](nsecs_t timestamp) {
718 mInterceptor->saveVSyncEvent(timestamp);
719 },
720 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800721 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200722 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800723
Steven Thomasb02664d2017-07-26 18:48:28 -0700724 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800725 getBE().mRenderEngine =
726 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
727 hasWideColorDisplay
728 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
729 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800730 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700731
732 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
733 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800734 getBE().mHwc.reset(
735 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700736 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800737 // Process any initial hotplug and resulting display changes.
738 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700739 const auto display = getDefaultDisplayDeviceLocked();
740 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
741 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
742 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800743
Lloyd Piquefcd86612017-12-14 17:15:36 -0800744 // make the default display GLContext current so that we can create textures
745 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700746 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800747
Steven Thomas050b2c82017-03-06 11:45:16 -0800748 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700749 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700750 // This callback is called from the vr flinger dispatch thread. We
751 // need to call signalTransaction(), which requires holding
752 // mStateLock when we're not on the main thread. Acquiring
753 // mStateLock from the vr flinger dispatch thread might trigger a
754 // deadlock in surface flinger (see b/66916578), so post a message
755 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700756 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700757 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
758 mVrFlingerRequestsDisplay = requestDisplay;
759 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700760 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800761 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700762 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
763 getHwComposer()
764 .getHwcDisplayId(display->getId())
765 .value_or(0),
766 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800767 if (!mVrFlinger) {
768 ALOGE("Failed to start vrflinger");
769 }
770 }
771
Lloyd Pique379adc12018-01-22 17:31:47 -0800772 mEventControlThread = std::make_unique<impl::EventControlThread>(
773 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700774
Mathias Agopian92a979a2012-08-02 18:32:23 -0700775 // initialize our drawing state
776 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700777
Andy McFadden13a082e2012-08-24 10:16:42 -0700778 // set initial conditions (e.g. unblank default device)
779 initializeDisplays();
780
David Sodmanbc815282017-11-05 18:57:52 -0800781 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700782
Wei Wangf9b05ee2017-07-19 20:59:39 -0700783 // Inform native graphics APIs whether the present timestamp is supported:
784 if (getHwComposer().hasCapability(
785 HWC2::Capability::PresentFenceIsNotReliable)) {
786 mStartPropertySetThread = new StartPropertySetThread(false);
787 } else {
788 mStartPropertySetThread = new StartPropertySetThread(true);
789 }
790
791 if (mStartPropertySetThread->Start() != NO_ERROR) {
792 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800793 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800794
Chia-I Wud49d6692018-06-27 07:17:41 +0800795 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
796 // is used to saturate legacy sRGB content. However, to make sure the same color under
797 // Display P3 will be saturated to the same color, we intentionally break the API spec
798 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
799 // such saturation matrix on Display P3 is understood fully, the API should always return
800 // identify matrix.
801 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
802 Dataspace::SRGB_LINEAR);
803
804 // we will apply this on Display P3.
805 if (mEnhancedSaturationMatrix != mat4()) {
806 ColorSpace srgb(ColorSpace::sRGB());
807 ColorSpace displayP3(ColorSpace::DisplayP3());
808 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
809 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
810 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
811 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800812
Dan Stoza9e56aa02015-11-02 13:00:03 -0800813 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700814}
815
Romain Guy11d63f42017-07-20 12:47:14 -0700816void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700817 Mutex::Autolock _l(mStateLock);
818
Romain Guy11d63f42017-07-20 12:47:14 -0700819 char value[PROPERTY_VALUE_MAX];
820
821 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800822 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700823 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800824 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100825
826 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700827 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700828}
829
Mathias Agopiana67e4182012-06-19 17:26:12 -0700830void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800831 // Start boot animation service by setting a property mailbox
832 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700833 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800834 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700835 if (mStartPropertySetThread->join() != NO_ERROR) {
836 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800837 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700838}
839
Mathias Agopian875d8e12013-06-07 15:35:48 -0700840size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800841 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700842}
843
Mathias Agopian875d8e12013-06-07 15:35:48 -0700844size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800845 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700846}
847
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800848// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800849
Jamie Gennis582270d2011-08-17 18:19:00 -0700850bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800851 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800852 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800853 return authenticateSurfaceTextureLocked(bufferProducer);
854}
855
856bool SurfaceFlinger::authenticateSurfaceTextureLocked(
857 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800858 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800859 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800860}
861
Brian Anderson6b376712017-04-04 10:51:39 -0700862status_t SurfaceFlinger::getSupportedFrameTimestamps(
863 std::vector<FrameEvent>* outSupported) const {
864 *outSupported = {
865 FrameEvent::REQUESTED_PRESENT,
866 FrameEvent::ACQUIRE,
867 FrameEvent::LATCH,
868 FrameEvent::FIRST_REFRESH_START,
869 FrameEvent::LAST_REFRESH_START,
870 FrameEvent::GPU_COMPOSITION_DONE,
871 FrameEvent::DEQUEUE_READY,
872 FrameEvent::RELEASE,
873 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700874 ConditionalLock _l(mStateLock,
875 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700876 if (!getHwComposer().hasCapability(
877 HWC2::Capability::PresentFenceIsNotReliable)) {
878 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
879 }
880 return NO_ERROR;
881}
882
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700883status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
884 Vector<DisplayInfo>* configs) {
885 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700886 return BAD_VALUE;
887 }
888
Jesse Hall692c7232012-11-08 15:41:56 -0800889 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700890 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
891 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700892 type = i;
893 break;
894 }
895 }
896
897 if (type < 0) {
898 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700899 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700900
Mathias Agopian8b736f12012-08-13 17:54:26 -0700901 // TODO: Not sure if display density should handled by SF any longer
902 class Density {
903 static int getDensityFromProperty(char const* propName) {
904 char property[PROPERTY_VALUE_MAX];
905 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800906 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700907 density = atoi(property);
908 }
909 return density;
910 }
911 public:
912 static int getEmuDensity() {
913 return getDensityFromProperty("qemu.sf.lcd_density"); }
914 static int getBuildDensity() {
915 return getDensityFromProperty("ro.sf.lcd_density"); }
916 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700917
Dan Stoza7f7da322014-05-02 15:26:25 -0700918 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700919
Steven Thomas6d8110b2017-08-31 18:24:21 -0700920 ConditionalLock _l(mStateLock,
921 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800922 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700923 DisplayInfo info = DisplayInfo();
924
Dan Stoza9e56aa02015-11-02 13:00:03 -0800925 float xdpi = hwConfig->getDpiX();
926 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700927
928 if (type == DisplayDevice::DISPLAY_PRIMARY) {
929 // The density of the device is provided by a build property
930 float density = Density::getBuildDensity() / 160.0f;
931 if (density == 0) {
932 // the build doesn't provide a density -- this is wrong!
933 // use xdpi instead
934 ALOGE("ro.sf.lcd_density must be defined as a build property");
935 density = xdpi / 160.0f;
936 }
937 if (Density::getEmuDensity()) {
938 // if "qemu.sf.lcd_density" is specified, it overrides everything
939 xdpi = ydpi = density = Density::getEmuDensity();
940 density /= 160.0f;
941 }
942 info.density = density;
943
944 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945 const auto display = getDefaultDisplayDeviceLocked();
946 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700947 } else {
948 // TODO: where should this value come from?
949 static const int TV_DENSITY = 213;
950 info.density = TV_DENSITY / 160.0f;
951 info.orientation = 0;
952 }
953
Dan Stoza9e56aa02015-11-02 13:00:03 -0800954 info.w = hwConfig->getWidth();
955 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700956 info.xdpi = xdpi;
957 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800958 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900959 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800960
Andy McFadden91b2ca82014-06-13 14:04:23 -0700961 // This is how far in advance a buffer must be queued for
962 // presentation at a given time. If you want a buffer to appear
963 // on the screen at time N, you must submit the buffer before
964 // (N - presentationDeadline).
965 //
966 // Normally it's one full refresh period (to give SF a chance to
967 // latch the buffer), but this can be reduced by configuring a
968 // DispSync offset. Any additional delays introduced by the hardware
969 // composer or panel must be accounted for here.
970 //
971 // We add an additional 1ms to allow for processing time and
972 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800973 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800974 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700975
976 // All non-virtual displays are currently considered secure.
977 info.secure = true;
978
Iris Chang7501ed62018-04-30 14:45:42 +0800979 if (type == DisplayDevice::DISPLAY_PRIMARY &&
980 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
981 std::swap(info.w, info.h);
982 }
983
Michael Wright28f24d02016-07-12 13:30:53 -0700984 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700985 }
986
Dan Stoza7f7da322014-05-02 15:26:25 -0700987 return NO_ERROR;
988}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700989
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700990status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
991 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700992 return BAD_VALUE;
993 }
994
995 // FIXME for now we always return stats for the primary display
996 memset(stats, 0, sizeof(*stats));
997 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
998 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
999 return NO_ERROR;
1000}
1001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001002int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
1003 const auto display = getDisplayDevice(displayToken);
1004 if (!display) {
1005 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +08001006 return BAD_VALUE;
1007 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -07001010}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001011
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001012void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
1013 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001014 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001015 return;
1016 }
1017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001019 ALOGW("Trying to set config for virtual display");
1020 return;
1021 }
1022
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001023 display->setActiveConfig(mode);
1024 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001025}
1026
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001027status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001028 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029 Vector<DisplayInfo> configs;
1030 getDisplayConfigs(displayToken, &configs);
1031 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
1032 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
1033 configs.size());
1034 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001035 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001036 const auto display = getDisplayDevice(displayToken);
1037 if (!display) {
1038 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
1039 displayToken.get());
1040 } else if (display->isVirtual()) {
1041 ALOGW("Attempt to set active config %d for virtual display", mode);
1042 } else {
1043 setActiveConfigInternal(display, mode);
1044 }
1045 }));
1046
Mathias Agopian888c8222012-08-04 21:10:38 -07001047 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001048}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001049status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1050 Vector<ColorMode>* outColorModes) {
1051 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001052 return BAD_VALUE;
1053 }
1054
Michael Wright28f24d02016-07-12 13:30:53 -07001055 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1057 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001058 type = i;
1059 break;
1060 }
1061 }
1062
1063 if (type < 0) {
1064 return type;
1065 }
1066
Peiyong Lina52f0292018-03-14 17:26:31 -07001067 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001068 {
1069 ConditionalLock _l(mStateLock,
1070 std::this_thread::get_id() != mMainThreadId);
1071 modes = getHwComposer().getColorModes(type);
1072 }
Michael Wright28f24d02016-07-12 13:30:53 -07001073 outColorModes->clear();
1074 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1075
1076 return NO_ERROR;
1077}
1078
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001079ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1080 if (const auto display = getDisplayDevice(displayToken)) {
1081 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001082 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001083 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001084}
1085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1087 Dataspace dataSpace, RenderIntent renderIntent) {
1088 ColorMode currentMode = display->getActiveColorMode();
1089 Dataspace currentDataSpace = display->getCompositionDataSpace();
1090 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001091
Peiyong Lin38e9a562018-04-10 16:24:20 -07001092 if (mode == currentMode && dataSpace == currentDataSpace &&
1093 renderIntent == currentRenderIntent) {
1094 return;
1095 }
1096
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001097 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001098 ALOGW("Trying to set config for virtual display");
1099 return;
1100 }
1101
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001102 display->setActiveColorMode(mode);
1103 display->setCompositionDataSpace(dataSpace);
1104 display->setActiveRenderIntent(renderIntent);
1105 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001106
1107 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001108 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1109 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001110}
1111
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001112status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001113 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001114 Vector<ColorMode> modes;
1115 getDisplayColorModes(displayToken, &modes);
1116 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1117 if (mode < ColorMode::NATIVE || !exists) {
1118 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1119 decodeColorMode(mode).c_str(), mode, displayToken.get());
1120 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001121 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122 const auto display = getDisplayDevice(displayToken);
1123 if (!display) {
1124 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1125 decodeColorMode(mode).c_str(), mode, displayToken.get());
1126 } else if (display->isVirtual()) {
1127 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1128 decodeColorMode(mode).c_str(), mode);
1129 } else {
1130 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1131 RenderIntent::COLORIMETRIC);
1132 }
1133 }));
1134
Michael Wright28f24d02016-07-12 13:30:53 -07001135 return NO_ERROR;
1136}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001137
Svetoslavd85084b2014-03-20 10:28:31 -07001138status_t SurfaceFlinger::clearAnimationFrameStats() {
1139 Mutex::Autolock _l(mStateLock);
1140 mAnimFrameTracker.clearStats();
1141 return NO_ERROR;
1142}
1143
1144status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1145 Mutex::Autolock _l(mStateLock);
1146 mAnimFrameTracker.getStats(outStats);
1147 return NO_ERROR;
1148}
1149
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001150status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1151 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001152 Mutex::Autolock _l(mStateLock);
1153
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001154 const auto display = getDisplayDeviceLocked(displayToken);
1155 if (!display) {
1156 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001157 return BAD_VALUE;
1158 }
1159
Peiyong Linfb069302018-04-25 14:34:31 -07001160 // At this point the DisplayDeivce should already be set up,
1161 // meaning the luminance information is already queried from
1162 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001163 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001164 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1165 capabilities.getDesiredMaxLuminance(),
1166 capabilities.getDesiredMaxAverageLuminance(),
1167 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001168
1169 return NO_ERROR;
1170}
1171
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001172status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001173 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001174 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001175
Chia-I Wu90f669f2017-10-05 14:24:41 -07001176 if (mInjectVSyncs == enable) {
1177 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001178 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001179
1180 if (enable) {
1181 ALOGV("VSync Injections enabled");
1182 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001183 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001184 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001185 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001186 impl::EventThread::InterceptVSyncsCallback(),
1187 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001188 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001189 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001190 } else {
1191 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001192 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001193 }
1194
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001195 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001196 }));
1197
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001198 return NO_ERROR;
1199}
1200
1201status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001202 Mutex::Autolock _l(mStateLock);
1203
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001204 if (!mInjectVSyncs) {
1205 ALOGE("VSync Injections not enabled");
1206 return BAD_VALUE;
1207 }
1208 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1209 ALOGV("Injecting VSync inside SurfaceFlinger");
1210 mVSyncInjector->onInjectSyncEvent(when);
1211 }
1212 return NO_ERROR;
1213}
1214
Lloyd Pique755e3192018-01-31 16:46:15 -08001215status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1216 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001217 IPCThreadState* ipc = IPCThreadState::self();
1218 const int pid = ipc->getCallingPid();
1219 const int uid = ipc->getCallingUid();
1220 if ((uid != AID_SHELL) &&
1221 !PermissionCache::checkPermission(sDump, pid, uid)) {
1222 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1223 return PERMISSION_DENIED;
1224 }
1225
1226 // Try to acquire a lock for 1s, fail gracefully
1227 const status_t err = mStateLock.timedLock(s2ns(1));
1228 const bool locked = (err == NO_ERROR);
1229 if (!locked) {
1230 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1231 return TIMED_OUT;
1232 }
1233
1234 outLayers->clear();
1235 mCurrentState.traverseInZOrder([&](Layer* layer) {
1236 outLayers->push_back(layer->getLayerDebugInfo());
1237 });
1238
1239 mStateLock.unlock();
1240 return NO_ERROR;
1241}
1242
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001243// ----------------------------------------------------------------------------
1244
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001245sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1246 ISurfaceComposer::VsyncSource vsyncSource) {
1247 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1248 return mSFEventThread->createEventConnection();
1249 } else {
1250 return mEventThread->createEventConnection();
1251 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001252}
1253
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001254// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001255
1256void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001257 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001258}
1259
1260void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001261 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001262}
1263
1264void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001265 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001266}
1267
1268void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001269 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001270 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001271}
1272
1273status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001274 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001275 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001276}
1277
1278status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001279 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001280 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001281 if (res == NO_ERROR) {
1282 msg->wait();
1283 }
1284 return res;
1285}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001286
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001287void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001288 do {
1289 waitForEvent();
1290 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001291}
1292
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001293void SurfaceFlinger::enableHardwareVsync() {
1294 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001295 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001297 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001298 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001299 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300}
1301
Jesse Hall948fe0c2013-10-14 12:56:09 -07001302void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001303 Mutex::Autolock _l(mHWVsyncLock);
1304
Jesse Hall948fe0c2013-10-14 12:56:09 -07001305 if (makeAvailable) {
1306 mHWVsyncAvailable = true;
1307 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001308 // Hardware vsync is not currently available, so abort the resync
1309 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001310 return;
1311 }
1312
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001313 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1314 if (!getHwComposer().isConnected(displayId)) {
1315 return;
1316 }
1317
1318 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001319 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001320
1321 mPrimaryDispSync.reset();
1322 mPrimaryDispSync.setPeriod(period);
1323
1324 if (!mPrimaryHWVsyncEnabled) {
1325 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001326 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001327 mPrimaryHWVsyncEnabled = true;
1328 }
1329}
1330
Jesse Hall948fe0c2013-10-14 12:56:09 -07001331void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001332 Mutex::Autolock _l(mHWVsyncLock);
1333 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001334 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001335 mPrimaryDispSync.endResync();
1336 mPrimaryHWVsyncEnabled = false;
1337 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001338 if (makeUnavailable) {
1339 mHWVsyncAvailable = false;
1340 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001341}
1342
Tim Murray4a4e4a22016-04-19 16:29:23 +00001343void SurfaceFlinger::resyncWithRateLimit() {
1344 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001345
1346 // No explicit locking is needed here since EventThread holds a lock while calling this method
1347 static nsecs_t sLastResyncAttempted = 0;
1348 const nsecs_t now = systemTime();
1349 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001350 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001351 }
Dan Stoza57164302017-05-08 14:03:54 -07001352 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001353}
1354
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001355void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1356 int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001357 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001358 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001359 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 return;
1361 }
1362
1363 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001364 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001365 return;
1366 }
1367
Jamie Gennisd1700752013-10-14 12:22:52 -07001368 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001369
Jamie Gennisd1700752013-10-14 12:22:52 -07001370 { // Scope for the lock
1371 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001372 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001373 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001374 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001375 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001376
1377 if (needsHwVsync) {
1378 enableHardwareVsync();
1379 } else {
1380 disableHardwareVsync(false);
1381 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001382}
1383
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001384void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001385 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1386 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001387}
1388
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001389void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001390 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001391 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001392 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001393
Lloyd Piqueba04e622017-12-14 17:11:26 -08001394 // Ignore events that do not have the right sequenceId.
1395 if (sequenceId != getBE().mComposerSequenceId) {
1396 return;
1397 }
1398
Steven Thomasb02664d2017-07-26 18:48:28 -07001399 // Only lock if we're not on the main thread. This function is normally
1400 // called on a hwbinder thread, but for the primary display it's called on
1401 // the main thread with the state lock already held, so don't attempt to
1402 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001403 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001404
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001405 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001406
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001407 if (std::this_thread::get_id() == mMainThreadId) {
1408 // Process all pending hot plug events immediately if we are on the main thread.
1409 processDisplayHotplugEventsLocked();
1410 }
1411
Lloyd Piqueba04e622017-12-14 17:11:26 -08001412 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001413}
1414
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001415void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001416 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001417 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001419 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001420 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001421}
1422
Dan Stoza9e56aa02015-11-02 13:00:03 -08001423void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001424 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001426 getHwComposer().setVsyncEnabled(disp,
1427 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001428}
1429
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001431void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001432 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001433 // Clear the drawing state so that the logic inside of
1434 // handleTransactionLocked will fire. It will determine the delta between
1435 // mCurrentState and mDrawingState and re-apply all changes when we make the
1436 // transition.
1437 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001438 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001439 mDisplays.clear();
1440}
1441
Steven Thomas050b2c82017-03-06 11:45:16 -08001442void SurfaceFlinger::updateVrFlinger() {
1443 if (!mVrFlinger)
1444 return;
1445 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001446 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001447 return;
1448 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001449
David Sodman105b7dc2017-11-04 20:28:14 -07001450 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001451 ALOGE("Vr flinger is only supported for remote hardware composer"
1452 " service connections. Ignoring request to transition to vr"
1453 " flinger.");
1454 mVrFlingerRequestsDisplay = false;
1455 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001456 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001457
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001458 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001459
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001460 const auto display = getDefaultDisplayDeviceLocked();
1461 LOG_ALWAYS_FATAL_IF(!display);
1462 const int currentDisplayPowerMode = display->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001463
Steven Thomasb02664d2017-07-26 18:48:28 -07001464 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001465 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001466 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001467
Steven Thomasb02664d2017-07-26 18:48:28 -07001468 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001469 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001470 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1471 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001472 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001473
David Sodman105b7dc2017-11-04 20:28:14 -07001474 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1475 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001476
1477 if (vrFlingerRequestsDisplay) {
1478 mVrFlinger->GrantDisplayOwnership();
1479 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001480 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001481 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001482
1483 mVisibleRegionsDirty = true;
1484 invalidateHwcGeometry();
1485
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001486 // Re-enable default display.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001487 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001488
Steven Thomasb02664d2017-07-26 18:48:28 -07001489 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001490 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001491 const nsecs_t period = activeConfig->getVsyncPeriod();
1492 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001493
Steven Thomasb02664d2017-07-26 18:48:28 -07001494 // Use phase of 0 since phase is not known.
1495 // Use latency of 0, which will snap to the ideal latency.
1496 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001497
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001498 android_atomic_or(1, &mRepaintEverything);
1499 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001500}
1501
Mathias Agopian4fec8732012-06-29 14:12:52 -07001502void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001503 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001504 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001505 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001506 bool frameMissed = !mHadClientComposition &&
1507 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001508 (mPreviousPresentFence->getSignalTime() ==
1509 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001510 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001511 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001512 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001513 mTimeStats.incrementMissedFrames();
1514 if (mPropagateBackpressure) {
1515 signalLayerUpdate();
1516 break;
1517 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001518 }
Dan Stoza50182882016-07-08 12:02:20 -07001519
Steven Thomas050b2c82017-03-06 11:45:16 -08001520 // Now that we're going to make it to the handleMessageTransaction()
1521 // call below it's safe to call updateVrFlinger(), which will
1522 // potentially trigger a display handoff.
1523 updateVrFlinger();
1524
Dan Stoza6b9454d2014-11-07 16:00:59 -08001525 bool refreshNeeded = handleMessageTransaction();
1526 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001527 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001528 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001529 // Signal a refresh if a transaction modified the window state,
1530 // a new buffer was latched, or if HWC has requested a full
1531 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001532 signalRefresh();
1533 }
1534 break;
1535 }
1536 case MessageQueue::REFRESH: {
1537 handleMessageRefresh();
1538 break;
1539 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001540 }
1541}
1542
Dan Stoza6b9454d2014-11-07 16:00:59 -08001543bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001544 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001545 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001546 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001547 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001548 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001549 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001550}
1551
Dan Stoza6b9454d2014-11-07 16:00:59 -08001552bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001553 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001554 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001555}
1556
1557void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001558 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001559
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001560 mRefreshPending = false;
1561
Chia-I Wu30505fb2018-03-26 16:20:31 -07001562 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001563
Chia-I Wu30505fb2018-03-26 16:20:31 -07001564 preComposition(refreshStartTime);
1565 rebuildLayerStacks();
1566 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001567 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001568 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001569 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001570 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001571 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001572
Dan Stozabfbffeb2016-07-21 14:49:33 -07001573 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001574 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001575 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001576 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001577 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001578 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001579
Dan Stoza9e56aa02015-11-02 13:00:03 -08001580 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001582
Mathias Agopiancd60f992012-08-16 16:28:27 -07001583void SurfaceFlinger::doDebugFlashRegions()
1584{
1585 // is debugging enabled
1586 if (CC_LIKELY(!mDebugRegion))
1587 return;
1588
1589 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001590 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001591 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001592 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001593 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001594 if (!dirtyRegion.isEmpty()) {
1595 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001596 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001597
1598 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001599 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001600 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001601 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1602
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001603 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001604 }
1605 }
1606 }
1607
1608 postFramebuffer();
1609
1610 if (mDebugRegion > 1) {
1611 usleep(mDebugRegion * 1000);
1612 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001613
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001614 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001615 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001616 continue;
1617 }
1618
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001619 status_t result = display->prepareFrame(*getBE().mHwc);
1620 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001621 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001622 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001623}
1624
Adrian Roos1e1a1282017-11-01 19:05:31 +01001625void SurfaceFlinger::doTracing(const char* where) {
1626 ATRACE_CALL();
1627 ATRACE_NAME(where);
1628 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001629 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001630 }
1631}
1632
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001633void SurfaceFlinger::logLayerStats() {
1634 ATRACE_CALL();
1635 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001636 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001637 if (display->isPrimary()) {
1638 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001639 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001640 }
1641 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001642
1643 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001644 }
1645}
1646
Chia-I Wu30505fb2018-03-26 16:20:31 -07001647void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001648{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001649 ATRACE_CALL();
1650 ALOGV("preComposition");
1651
Mathias Agopiancd60f992012-08-16 16:28:27 -07001652 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001653 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001654 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001655 needExtraInvalidate = true;
1656 }
Robert Carr2047fae2016-11-28 14:09:09 -08001657 });
1658
Mathias Agopiancd60f992012-08-16 16:28:27 -07001659 if (needExtraInvalidate) {
1660 signalLayerUpdate();
1661 }
1662}
1663
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001664void SurfaceFlinger::updateCompositorTiming(
1665 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1666 std::shared_ptr<FenceTime>& presentFenceTime) {
1667 // Update queue of past composite+present times and determine the
1668 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001669 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001670 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001671 while (!getBE().mCompositePresentTimes.empty()) {
1672 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001673 // Cached values should have been updated before calling this method,
1674 // which helps avoid duplicate syscalls.
1675 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1676 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1677 break;
1678 }
1679 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001680 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001681 }
1682
1683 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001684 while (getBE().mCompositePresentTimes.size() > 16) {
1685 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001686 }
1687
Brian Andersond0010582017-03-07 13:20:31 -08001688 setCompositorTimingSnapped(
1689 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1690}
1691
1692void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1693 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001694 // Integer division and modulo round toward 0 not -inf, so we need to
1695 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001696 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001697 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1698 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1699
Brian Andersond0010582017-03-07 13:20:31 -08001700 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1701 if (idealLatency <= 0) {
1702 idealLatency = vsyncInterval;
1703 }
1704
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001705 // Snap the latency to a value that removes scheduling jitter from the
1706 // composition and present times, which often have >1ms of jitter.
1707 // Reducing jitter is important if an app attempts to extrapolate
1708 // something (such as user input) to an accurate diasplay time.
1709 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1710 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001711 nsecs_t bias = vsyncInterval / 2;
1712 int64_t extraVsyncs =
1713 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1714 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1715 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001716
David Sodman99974d22017-11-28 12:04:33 -08001717 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1718 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1719 getBE().mCompositorTiming.interval = vsyncInterval;
1720 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001721}
1722
Chia-I Wu30505fb2018-03-26 16:20:31 -07001723void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001724{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001725 ATRACE_CALL();
1726 ALOGV("postComposition");
1727
Brian Anderson3546a3f2016-07-14 11:51:14 -07001728 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001729 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001730 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001731 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001732 }
1733
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001734 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001735 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001736
David Sodman73beded2017-11-15 11:56:06 -08001737 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001738 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001739 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001740 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001741 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001742 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001743 } else {
1744 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1745 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001746
David Sodman73beded2017-11-15 11:56:06 -08001747 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001748 mPreviousPresentFence =
1749 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1750 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001751 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001752
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001753 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1754 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1755
Chia-I Wu30505fb2018-03-26 16:20:31 -07001756 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001757 // when we started doing work for this frame, but that should be okay
1758 // since updateCompositorTiming has snapping logic.
1759 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001760 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001761 CompositorTiming compositorTiming;
1762 {
David Sodman99974d22017-11-28 12:04:33 -08001763 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1764 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001765 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001766
Robert Carr2047fae2016-11-28 14:09:09 -08001767 mDrawingState.traverseInZOrder([&](Layer* layer) {
1768 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001769 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001770 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001771 recordBufferingStats(layer->getName().string(),
1772 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001773 }
Robert Carr2047fae2016-11-28 14:09:09 -08001774 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001775
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001776 if (presentFenceTime->isValid()) {
1777 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001778 enableHardwareVsync();
1779 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001780 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001781 }
1782 }
1783
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001784 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001785 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001786 enableHardwareVsync();
1787 }
1788 }
1789
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001790 if (mAnimCompositionPending) {
1791 mAnimCompositionPending = false;
1792
Brian Anderson4e606e32017-03-16 15:34:57 -07001793 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001794 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001795 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001796 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001797 // The HWC doesn't support present fences, so use the refresh
1798 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001799 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001800 mAnimFrameTracker.setActualPresentTime(presentTime);
1801 }
1802 mAnimFrameTracker.advanceFrame();
1803 }
Dan Stozab90cf072015-03-05 11:05:59 -08001804
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001805 mTimeStats.incrementTotalFrames();
1806 if (mHadClientComposition) {
1807 mTimeStats.incrementClientCompositionFrames();
1808 }
1809
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001810 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001811 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001812 return;
1813 }
1814
1815 nsecs_t currentTime = systemTime();
1816 if (mHasPoweredOff) {
1817 mHasPoweredOff = false;
1818 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001819 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001820 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001821 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1822 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001823 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001824 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001825 }
David Sodman4a36e932017-11-07 14:29:47 -08001826 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001827 }
David Sodman4a36e932017-11-07 14:29:47 -08001828 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001829
1830 {
1831 std::lock_guard lock(mTexturePoolMutex);
1832 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1833 if (refillCount > 0) {
1834 const size_t offset = mTexturePool.size();
1835 mTexturePool.resize(mTexturePoolSize);
1836 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1837 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1838 }
1839 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001840}
1841
1842void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001843 ATRACE_CALL();
1844 ALOGV("rebuildLayerStacks");
1845
Mathias Agopiancd60f992012-08-16 16:28:27 -07001846 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001847 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001848 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001849 mVisibleRegionsDirty = false;
1850 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001851
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001852 for (const auto& pair : mDisplays) {
1853 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001854 Region opaqueRegion;
1855 Region dirtyRegion;
1856 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001857 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001858 const Transform& tr = display->getTransform();
1859 const Rect bounds = display->getBounds();
1860 if (display->isPoweredOn()) {
1861 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001862
Jeff Sharkey76488112017-02-27 14:15:18 -07001863 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001864 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001865 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001866 Region drawRegion(tr.transform(
1867 layer->visibleNonTransparentRegion));
1868 drawRegion.andSelf(bounds);
1869 if (!drawRegion.isEmpty()) {
1870 layersSortedByZ.add(layer);
1871 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001872 // Clear out the HWC layer if this layer was
1873 // previously visible, but no longer is
Dominik Laskowski7e045462018-05-30 13:02:02 -07001874 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001875 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001876 } else {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001877 // WM changes display->layerStack upon sleep/awake.
Chia-I Wu30505fb2018-03-26 16:20:31 -07001878 // Here we make sure we delete the HWC layers even if
1879 // WM changed their layer stack.
Dominik Laskowski7e045462018-05-30 13:02:02 -07001880 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001881 }
1882
1883 // If a layer is not going to get a release fence because
1884 // it is invisible, but it is also going to release its
1885 // old buffer, add it to the list of layers needing
1886 // fences.
1887 if (hwcLayerDestroyed) {
1888 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1889 mLayersWithQueuedFrames.cend(), layer);
1890 if (found != mLayersWithQueuedFrames.cend()) {
1891 layersNeedingFences.add(layer);
1892 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001893 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001894 });
1895 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001896 display->setVisibleLayersSortedByZ(layersSortedByZ);
1897 display->setLayersNeedingFences(layersNeedingFences);
1898 display->undefinedRegion.set(bounds);
1899 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1900 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001901 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001902 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001903}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001904
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001905// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001906// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001907// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001908// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001909// The returned HDR data space is one of
1910// - Dataspace::UNKNOWN
1911// - Dataspace::BT2020_HLG
1912// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001913Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1914 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001915 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001916 *outHdrDataSpace = Dataspace::UNKNOWN;
1917
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001918 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001919 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001920 case Dataspace::V0_SCRGB:
1921 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001922 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001923 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001924 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001925 case Dataspace::BT2020_PQ:
1926 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001927 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001928 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001929 case Dataspace::BT2020_HLG:
1930 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001931 // When there's mixed PQ content and HLG content, we set the HDR
1932 // data space to be BT2020_PQ and convert HLG to PQ.
1933 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1934 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001935 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001936 break;
1937 default:
1938 break;
1939 }
Romain Guy54f154a2017-10-24 21:40:32 +01001940 }
1941
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001942 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001943}
1944
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001945// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001946void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1947 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001948 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1949 *outMode = ColorMode::NATIVE;
1950 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001951 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001952 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001953 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001954
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001955 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001956 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001957
Peiyong Lindfde5112018-06-05 10:58:41 -07001958 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001959 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001960 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001961 if (isHdr) {
1962 bestDataSpace = hdrDataSpace;
1963 }
1964
Chia-I Wu0d711262018-05-21 15:19:35 -07001965 RenderIntent intent;
1966 switch (mDisplayColorSetting) {
1967 case DisplayColorSetting::MANAGED:
1968 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001969 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001970 break;
1971 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001972 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001973 break;
1974 default: // vendor display color setting
1975 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1976 break;
1977 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001978
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001979 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001980}
1981
Chia-I Wu30505fb2018-03-26 16:20:31 -07001982void SurfaceFlinger::setUpHWComposer() {
1983 ATRACE_CALL();
1984 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001985
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001986 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001987 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
1988 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1989 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07001990
1991 // If nothing has changed (!dirty), don't recompose.
1992 // If something changed, but we don't currently have any visible layers,
1993 // and didn't when we last did a composition, then skip it this time.
1994 // The second rule does two things:
1995 // - When all layers are removed from a display, we'll emit one black
1996 // frame, then nothing more until we get new layers.
1997 // - When a display is created with a private layer stack, we won't
1998 // emit any black frames until a layer is added to the layer stack.
1999 bool mustRecompose = dirty && !(empty && wasEmpty);
2000
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002001 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002002 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
2003 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07002004
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002005 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002006
2007 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002008 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07002009 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002010 }
2011
Chia-I Wu30505fb2018-03-26 16:20:31 -07002012 // build the h/w work list
2013 if (CC_UNLIKELY(mGeometryInvalid)) {
2014 mGeometryInvalid = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002015 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002016 const auto displayId = display->getId();
2017 if (displayId >= 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002018 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
Chia-I Wu30505fb2018-03-26 16:20:31 -07002019 for (size_t i = 0; i < currentLayers.size(); i++) {
2020 const auto& layer = currentLayers[i];
Dominik Laskowski7e045462018-05-30 13:02:02 -07002021 if (!layer->hasHwcLayer(displayId)) {
2022 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
2023 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002024 continue;
2025 }
2026 }
2027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002028 layer->setGeometry(display, i);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002029 if (mDebugDisableHWC || mDebugRegion) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002030 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002031 }
2032 }
2033 }
2034 }
2035 }
2036
Chia-I Wu30505fb2018-03-26 16:20:31 -07002037 // Set the per-frame data
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002038 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002039 const auto displayId = display->getId();
2040 if (displayId < 0) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002041 continue;
2042 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002043
Chia-I Wu28f320b2018-05-03 11:02:56 -07002044 if (mDrawingState.colorMatrixChanged) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002045 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002046 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002047 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002048 displayId, result);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002049 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002050 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu692e0832018-06-05 15:46:58 -07002051 if (layer->isHdrY410()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002052 layer->forceClientComposition(displayId);
Chia-I Wu692e0832018-06-05 15:46:58 -07002053 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2054 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
2055 !display->hasHDR10Support()) {
2056 layer->forceClientComposition(displayId);
2057 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2058 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2059 !display->hasHLGSupport()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002060 layer->forceClientComposition(displayId);
Peiyong Linf59a7192018-04-25 11:19:31 -07002061 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002062
Dominik Laskowski7e045462018-05-30 13:02:02 -07002063 if (layer->getForceClientComposition(displayId)) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002064 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002065 layer->setCompositionType(displayId, HWC2::Composition::Client);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002066 continue;
2067 }
2068
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002069 layer->setPerFrameData(display);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002070 }
2071
2072 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002073 ColorMode colorMode;
2074 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002075 RenderIntent renderIntent;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002076 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
2077 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002078 }
2079 }
2080
Chia-I Wu28f320b2018-05-03 11:02:56 -07002081 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07002082
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002083 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002084 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002085 continue;
2086 }
2087
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002088 status_t result = display->prepareFrame(*getBE().mHwc);
2089 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002090 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002091 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002092}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002093
Mathias Agopiancd60f992012-08-16 16:28:27 -07002094void SurfaceFlinger::doComposition() {
2095 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002096 ALOGV("doComposition");
2097
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002098 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002099 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002100 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002101 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002102 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002103
2104 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002105 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002106
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002107 display->dirtyRegion.clear();
2108 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002109 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002110 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002111 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002112}
2113
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002114void SurfaceFlinger::postFramebuffer()
2115{
Mathias Agopian841cde52012-03-01 15:44:37 -08002116 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002117 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002118
Mathias Agopiana44b0412011-10-16 18:46:35 -07002119 const nsecs_t now = systemTime();
2120 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002121
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002122 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002123 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002124 continue;
2125 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002126 const auto displayId = display->getId();
2127 if (displayId >= 0) {
2128 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002129 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002130 display->onSwapBuffersCompleted();
2131 display->makeCurrent();
2132 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002133 // The layer buffer from the previous frame (if any) is released
2134 // by HWC only when the release fence from this frame (if any) is
2135 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002136 auto hwcLayer = layer->getHwcLayer(displayId);
2137 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002138
2139 // If the layer was client composited in the previous frame, we
2140 // need to merge with the previous client target acquire fence.
2141 // Since we do not track that, always merge with the current
2142 // client target acquire fence when it is available, even though
2143 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002144 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002145 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002146 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002147 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002148
David Sodmanb8af7922017-12-21 15:17:55 -08002149 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002150 }
Chia-I Wu83806892017-11-16 10:50:20 -08002151
2152 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002153 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002154 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002155 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002156 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002157 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002158 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002159 }
2160 }
2161
Dominik Laskowski7e045462018-05-30 13:02:02 -07002162 if (displayId >= 0) {
2163 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002164 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002165 }
2166
Mathias Agopiana44b0412011-10-16 18:46:35 -07002167 mLastSwapBufferTime = systemTime() - now;
2168 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002169
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002170 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002171 const auto display = getDefaultDisplayDeviceLocked();
2172 if (display && getHwComposer().isConnected(display->getId())) {
2173 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002174 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2175 logFrameStats();
2176 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002177 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002178}
2179
Mathias Agopian87baae12012-07-31 12:38:26 -07002180void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002181{
Mathias Agopian841cde52012-03-01 15:44:37 -08002182 ATRACE_CALL();
2183
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002184 // here we keep a copy of the drawing state (that is the state that's
2185 // going to be overwritten by handleTransactionLocked()) outside of
2186 // mStateLock so that the side-effects of the State assignment
2187 // don't happen with mStateLock held (which can cause deadlocks).
2188 State drawingState(mDrawingState);
2189
Mathias Agopianca4d3602011-05-19 15:38:14 -07002190 Mutex::Autolock _l(mStateLock);
2191 const nsecs_t now = systemTime();
2192 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002193
Mathias Agopianca4d3602011-05-19 15:38:14 -07002194 // Here we're guaranteed that some transaction flags are set
2195 // so we can call handleTransactionLocked() unconditionally.
2196 // We call getTransactionFlags(), which will also clear the flags,
2197 // with mStateLock held to guarantee that mCurrentState won't change
2198 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002199
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002200 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002201 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002202 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002203
Mathias Agopianca4d3602011-05-19 15:38:14 -07002204 mLastTransactionTime = systemTime() - now;
2205 mDebugInTransaction = 0;
2206 invalidateHwcGeometry();
2207 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002208}
2209
Dominik Laskowski7e045462018-05-30 13:02:02 -07002210DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002211 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002212 // Figure out whether the event is for the primary display or an
2213 // external display by matching the Hwc display id against one for a
2214 // connected display. If we did not find a match, we then check what
2215 // displays are not already connected to determine the type. If we don't
2216 // have a connected primary display, we assume the new display is meant to
2217 // be the primary display, and then if we don't have an external display,
2218 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002219 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2220 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002221 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002222 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002223 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002224 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002225 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002226 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002227 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002228 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002229 return DisplayDevice::DISPLAY_EXTERNAL;
2230 }
2231
2232 return DisplayDevice::DISPLAY_ID_INVALID;
2233}
2234
Lloyd Piqueba04e622017-12-14 17:11:26 -08002235void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2236 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002237 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002238 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002239 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002240 continue;
2241 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002242
2243 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2244 ALOGE("External displays are not supported by the vr hardware composer.");
2245 continue;
2246 }
2247
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002248 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002249 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002250 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002251 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002252 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002253
2254 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002255 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002256 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002257 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002258 DisplayDeviceState info;
2259 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002260 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2261 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002262 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002263 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002264 mInterceptor->saveDisplayCreation(info);
2265 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002266 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002267 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002268
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002269 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002270 if (idx >= 0) {
2271 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002272 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002273 mCurrentState.displays.removeItemsAt(idx);
2274 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002275 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002276 }
2277
2278 processDisplayChangesLocked();
2279 }
2280
2281 mPendingHotplugEvents.clear();
2282}
2283
Lloyd Pique99d3da52018-01-22 17:48:03 -08002284sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002285 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002286 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002287 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002288 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002289
Lloyd Pique99d3da52018-01-22 17:48:03 -08002290 if (hasWideColorDisplay) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002291 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002292 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002293 if (isWideColorMode(colorMode)) {
2294 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002295 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002296
Dominik Laskowski7e045462018-05-30 13:02:02 -07002297 std::vector<RenderIntent> renderIntents =
2298 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002299 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002300 }
2301 }
2302
Peiyong Lin62665892018-04-16 11:07:44 -07002303 HdrCapabilities hdrCapabilities;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002304 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002305
2306 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2307 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2308
2309 /*
2310 * Create our display's surface
2311 */
2312 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2313 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002314 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002315 renderSurface->setNativeWindow(nativeWindow.get());
2316 const int displayWidth = renderSurface->queryWidth();
2317 const int displayHeight = renderSurface->queryHeight();
2318
2319 // Make sure that composition can never be stalled by a virtual display
2320 // consumer that isn't processing buffers fast enough. We have to do this
2321 // in two places:
2322 // * Here, in case the display is composed entirely by HWC.
2323 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2324 // window's swap interval in eglMakeCurrent, so they'll override the
2325 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002326 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002327 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2328 }
2329
2330 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002331 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002332
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002333 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002334 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2335 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2336 displayHeight, hasWideColorGamut, hdrCapabilities,
2337 getHwComposer().getSupportedPerFrameMetadata(displayId),
2338 hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002339
2340 if (maxFrameBufferAcquiredBuffers >= 3) {
2341 nativeWindowSurface->preallocateBuffers();
2342 }
2343
2344 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002345 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2346 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002347 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002348 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002349 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002350 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002351 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002352 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002353 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002354 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002355 display->setLayerStack(state.layerStack);
2356 display->setProjection(state.orientation, state.viewport, state.frame);
2357 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002358
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002359 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002360}
2361
Lloyd Pique347200f2017-12-14 17:00:15 -08002362void SurfaceFlinger::processDisplayChangesLocked() {
2363 // here we take advantage of Vector's copy-on-write semantics to
2364 // improve performance by skipping the transaction entirely when
2365 // know that the lists are identical
2366 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2367 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2368 if (!curr.isIdenticalTo(draw)) {
2369 mVisibleRegionsDirty = true;
2370 const size_t cc = curr.size();
2371 size_t dc = draw.size();
2372
2373 // find the displays that were removed
2374 // (ie: in drawing state but not in current state)
2375 // also handle displays that changed
2376 // (ie: displays that are in both lists)
2377 for (size_t i = 0; i < dc;) {
2378 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2379 if (j < 0) {
2380 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002381 // Call makeCurrent() on the primary display so we can
2382 // be sure that nothing associated with this display
2383 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002384 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2385 defaultDisplay->makeCurrent();
2386 }
2387 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2388 display->disconnect(getHwComposer());
2389 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002390 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2391 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2392 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2393 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2394 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002395 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002396 } else {
2397 // this display is in both lists. see if something changed.
2398 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002399 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002400 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2401 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2402 if (state_binder != draw_binder) {
2403 // changing the surface is like destroying and
2404 // recreating the DisplayDevice, so we just remove it
2405 // from the drawing state, so that it get re-added
2406 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002407 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2408 display->disconnect(getHwComposer());
2409 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002410 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002411 mDrawingState.displays.removeItemsAt(i);
2412 dc--;
2413 // at this point we must loop to the next item
2414 continue;
2415 }
2416
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002417 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002418 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002419 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002420 }
2421 if ((state.orientation != draw[i].orientation) ||
2422 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002423 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002424 }
2425 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002426 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002427 }
2428 }
2429 }
2430 ++i;
2431 }
2432
2433 // find displays that were added
2434 // (ie: in current state but not in drawing state)
2435 for (size_t i = 0; i < cc; i++) {
2436 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2437 const DisplayDeviceState& state(curr[i]);
2438
2439 sp<DisplaySurface> dispSurface;
2440 sp<IGraphicBufferProducer> producer;
2441 sp<IGraphicBufferProducer> bqProducer;
2442 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002443 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002444
Dominik Laskowski7e045462018-05-30 13:02:02 -07002445 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002446 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002447 // Virtual displays without a surface are dormant:
2448 // they have external state (layer stack, projection,
2449 // etc.) but no internal state (i.e. a DisplayDevice).
2450 if (state.surface != nullptr) {
2451 // Allow VR composer to use virtual displays.
2452 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2453 int width = 0;
2454 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2455 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2456 int height = 0;
2457 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2458 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2459 int intFormat = 0;
2460 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2461 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002462 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002463
Dominik Laskowski7e045462018-05-30 13:02:02 -07002464 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2465 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002466 }
2467
2468 // TODO: Plumb requested format back up to consumer
2469
2470 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002471 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002472 bqProducer, bqConsumer,
2473 state.displayName);
2474
2475 dispSurface = vds;
2476 producer = vds;
2477 }
2478 } else {
2479 ALOGE_IF(state.surface != nullptr,
2480 "adding a supported display, but rendering "
2481 "surface is provided (%p), ignoring it",
2482 state.surface.get());
2483
Dominik Laskowski7e045462018-05-30 13:02:02 -07002484 displayId = state.type;
2485 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002486 producer = bqProducer;
2487 }
2488
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002489 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002490 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002491 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002492 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002493 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002494 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002495 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2496 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2497 true);
2498 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2499 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2500 true);
2501 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002502 }
2503 }
2504 }
2505 }
2506 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002507
2508 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002509}
2510
Mathias Agopian87baae12012-07-31 12:38:26 -07002511void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002512{
Dan Stoza7dde5992015-05-22 09:51:44 -07002513 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002514 mCurrentState.traverseInZOrder([](Layer* layer) {
2515 layer->notifyAvailableFrames();
2516 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002517
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518 /*
2519 * Traversal of the children
2520 * (perform the transaction for each of them if needed)
2521 */
2522
Mathias Agopian3559b072012-08-15 13:46:03 -07002523 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002524 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002525 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002526 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002527
2528 const uint32_t flags = layer->doTransaction(0);
2529 if (flags & Layer::eVisibleRegion)
2530 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002531 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002532 }
2533
2534 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002535 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536 */
2537
Mathias Agopiane57f2922012-08-09 16:29:12 -07002538 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002539 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002540 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002541 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002542
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002543 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002544 // The transform hint might have changed for some layers
2545 // (either because a display has changed, or because a layer
2546 // as changed).
2547 //
2548 // Walk through all the layers in currentLayers,
2549 // and update their transform hint.
2550 //
2551 // If a layer is visible only on a single display, then that
2552 // display is used to calculate the hint, otherwise we use the
2553 // default display.
2554 //
2555 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2556 // the hint is set before we acquire a buffer from the surface texture.
2557 //
2558 // NOTE: layer transactions have taken place already, so we use their
2559 // drawing state. However, SurfaceFlinger's own transaction has not
2560 // happened yet, so we must use the current state layer list
2561 // (soon to become the drawing state list).
2562 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002563 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002564 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002565 bool first = true;
2566 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002567 // NOTE: we rely on the fact that layers are sorted by
2568 // layerStack first (so we don't have to traverse the list
2569 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002570 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002571 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002572 currentlayerStack = layerStack;
2573 // figure out if this layerstack is mirrored
2574 // (more than one display) if so, pick the default display,
2575 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002576 hintDisplay = nullptr;
2577 for (const auto& [token, display] : mDisplays) {
2578 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2579 if (hintDisplay) {
2580 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002581 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002582 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002583 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002584 }
2585 }
2586 }
2587 }
Chet Haase91d25932013-04-11 15:24:55 -07002588
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002589 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002590 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2591 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002592
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002593 // could be null when this layer is using a layerStack
2594 // that is not visible on any display. Also can occur at
2595 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002596 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002597 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002598
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002599 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002600 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002601 if (hintDisplay) {
2602 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002603 }
Robert Carr2047fae2016-11-28 14:09:09 -08002604
2605 first = false;
2606 });
Mathias Agopian84300952012-11-21 16:02:13 -08002607 }
2608
2609
Mathias Agopian3559b072012-08-15 13:46:03 -07002610 /*
2611 * Perform our own transaction if needed
2612 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002613
2614 if (mLayersAdded) {
2615 mLayersAdded = false;
2616 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002617 mVisibleRegionsDirty = true;
2618 }
2619
2620 // some layers might have been removed, so
2621 // we need to update the regions they're exposing.
2622 if (mLayersRemoved) {
2623 mLayersRemoved = false;
2624 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002625 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002626 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002627 // this layer is not visible anymore
2628 // TODO: we could traverse the tree from front to back and
2629 // compute the actual visible region
2630 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002631 Region visibleReg;
2632 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002633 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002634 }
Robert Carr2047fae2016-11-28 14:09:09 -08002635 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636 }
2637
2638 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002639
2640 updateCursorAsync();
2641}
2642
2643void SurfaceFlinger::updateCursorAsync()
2644{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002645 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002646 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002647 continue;
2648 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002649
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002650 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2651 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002652 }
2653 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002654}
2655
2656void SurfaceFlinger::commitTransaction()
2657{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002658 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002659 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002660 for (const auto& l : mLayersPendingRemoval) {
2661 recordBufferingStats(l->getName().string(),
2662 l->getOccupancyHistory(true));
2663 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002664 }
2665 mLayersPendingRemoval.clear();
2666 }
2667
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002668 // If this transaction is part of a window animation then the next frame
2669 // we composite should be considered an animation as well.
2670 mAnimCompositionPending = mAnimTransactionPending;
2671
Mathias Agopian4fec8732012-06-29 14:12:52 -07002672 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002673 // clear the "changed" flags in current state
2674 mCurrentState.colorMatrixChanged = false;
2675
Robert Carr1f0a16a2016-10-24 16:27:39 -07002676 mDrawingState.traverseInZOrder([](Layer* layer) {
2677 layer->commitChildList();
2678 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002679 mTransactionPending = false;
2680 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002681 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682}
2683
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002684void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2685 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002686 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002687 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002688
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002689 Region aboveOpaqueLayers;
2690 Region aboveCoveredLayers;
2691 Region dirty;
2692
Mathias Agopian87baae12012-07-31 12:38:26 -07002693 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002694
Robert Carr2047fae2016-11-28 14:09:09 -08002695 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002696 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002697 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698
Jesse Hall01e29052013-02-19 16:13:35 -08002699 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002700 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002701 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002702 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002703
Mathias Agopianab028732010-03-16 16:41:46 -07002704 /*
2705 * opaqueRegion: area of a surface that is fully opaque.
2706 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002707 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002708
2709 /*
2710 * visibleRegion: area of a surface that is visible on screen
2711 * and not fully transparent. This is essentially the layer's
2712 * footprint minus the opaque regions above it.
2713 * Areas covered by a translucent surface are considered visible.
2714 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002716
2717 /*
2718 * coveredRegion: area of a surface that is covered by all
2719 * visible regions above it (which includes the translucent areas).
2720 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002722
Jesse Halla8026d22012-09-25 13:25:04 -07002723 /*
2724 * transparentRegion: area of a surface that is hinted to be completely
2725 * transparent. This is only used to tell when the layer has no visible
2726 * non-transparent regions and can be removed from the layer list. It
2727 * does not affect the visibleRegion of this layer or any layers
2728 * beneath it. The hint may not be correct if apps don't respect the
2729 * SurfaceView restrictions (which, sadly, some don't).
2730 */
2731 Region transparentRegion;
2732
Mathias Agopianab028732010-03-16 16:41:46 -07002733
2734 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002735 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002736 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002737 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002739 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002740 if (!visibleRegion.isEmpty()) {
2741 // Remove the transparent area from the visible region
2742 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002743 if (tr.preserveRects()) {
2744 // transform the transparent region
2745 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002746 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002747 // transformation too complex, can't do the
2748 // transparent region optimization.
2749 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002750 }
Mathias Agopianab028732010-03-16 16:41:46 -07002751 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752
Mathias Agopianab028732010-03-16 16:41:46 -07002753 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002754 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002755 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002756 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2757 // the opaque region is the layer's footprint
2758 opaqueRegion = visibleRegion;
2759 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760 }
2761 }
2762
Robert Carre5f4f692018-01-12 13:12:28 -08002763 if (visibleRegion.isEmpty()) {
2764 layer->clearVisibilityRegions();
2765 return;
2766 }
2767
Mathias Agopianab028732010-03-16 16:41:46 -07002768 // Clip the covered region to the visible region
2769 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2770
2771 // Update aboveCoveredLayers for next (lower) layer
2772 aboveCoveredLayers.orSelf(visibleRegion);
2773
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774 // subtract the opaque region covered by the layers above us
2775 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776
2777 // compute this layer's dirty region
2778 if (layer->contentDirty) {
2779 // we need to invalidate the whole region
2780 dirty = visibleRegion;
2781 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002782 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783 layer->contentDirty = false;
2784 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002785 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002786 * the exposed region consists of two components:
2787 * 1) what's VISIBLE now and was COVERED before
2788 * 2) what's EXPOSED now less what was EXPOSED before
2789 *
2790 * note that (1) is conservative, we start with the whole
2791 * visible region but only keep what used to be covered by
2792 * something -- which mean it may have been exposed.
2793 *
2794 * (2) handles areas that were not covered by anything but got
2795 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002796 */
Mathias Agopianab028732010-03-16 16:41:46 -07002797 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002798 const Region oldVisibleRegion = layer->visibleRegion;
2799 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002800 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2801 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802 }
2803 dirty.subtractSelf(aboveOpaqueLayers);
2804
2805 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002806 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807
Mathias Agopianab028732010-03-16 16:41:46 -07002808 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002810
Jesse Halla8026d22012-09-25 13:25:04 -07002811 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812 layer->setVisibleRegion(visibleRegion);
2813 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002814 layer->setVisibleNonTransparentRegion(
2815 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002816 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817
Mathias Agopian87baae12012-07-31 12:38:26 -07002818 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002819}
2820
Chia-I Wuab0c3192017-08-01 11:29:00 -07002821void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002822 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002823 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2824 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002825 }
2826 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002827}
2828
Dan Stoza6b9454d2014-11-07 16:00:59 -08002829bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002830{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002831 ALOGV("handlePageFlip");
2832
Brian Andersond6927fb2016-07-23 23:37:30 -07002833 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002834
Mathias Agopian4fec8732012-06-29 14:12:52 -07002835 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002836 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002837 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002838
2839 // Store the set of layers that need updates. This set must not change as
2840 // buffers are being latched, as this could result in a deadlock.
2841 // Example: Two producers share the same command stream and:
2842 // 1.) Layer 0 is latched
2843 // 2.) Layer 0 gets a new frame
2844 // 2.) Layer 1 gets a new frame
2845 // 3.) Layer 1 is latched.
2846 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2847 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002848 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002849 if (layer->hasQueuedFrame()) {
2850 frameQueued = true;
2851 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002852 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002853 } else {
2854 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002855 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002856 } else {
2857 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002858 }
Robert Carr2047fae2016-11-28 14:09:09 -08002859 });
2860
Dan Stoza9e56aa02015-11-02 13:00:03 -08002861 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002862 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002863 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002864 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002865 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002866 newDataLatched = true;
2867 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002868 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002869
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002870 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002871
2872 // If we will need to wake up at some time in the future to deal with a
2873 // queued frame that shouldn't be displayed during this vsync period, wake
2874 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002875 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002876 signalLayerUpdate();
2877 }
2878
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002879 // enter boot animation on first buffer latch
2880 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2881 ALOGI("Enter boot animation");
2882 mBootStage = BootStage::BOOTANIMATION;
2883 }
2884
Dan Stoza6b9454d2014-11-07 16:00:59 -08002885 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002886 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887}
2888
Mathias Agopianad456f92011-01-13 17:53:01 -08002889void SurfaceFlinger::invalidateHwcGeometry()
2890{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002891 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002892}
2893
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002894void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2895 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002896 // We only need to actually compose the display if:
2897 // 1) It is being handled by hardware composer, which may need this to
2898 // keep its virtual display state machine in sync, or
2899 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002900 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002901 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002902 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002903 return;
2904 }
2905
Dan Stoza9e56aa02015-11-02 13:00:03 -08002906 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002907 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002908
2909 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002910 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002911}
2912
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002913bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002914 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002915
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002916 const Region bounds(display->bounds());
2917 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002918 const auto displayId = display->getId();
2919 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002920 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002921
Chia-I Wu8e50e692018-05-04 10:12:37 -07002922 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002923 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002924
Dan Stoza9e56aa02015-11-02 13:00:03 -08002925 if (hasClientComposition) {
2926 ALOGV("hasClientComposition");
2927
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002928 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002929 if (display->hasWideColorGamut()) {
2930 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002931 }
2932 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002933 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002934 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002935
Dominik Laskowski7e045462018-05-30 13:02:02 -07002936 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002937 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2938 HWC2::Capability::SkipClientColorTransform);
2939
Chia-I Wud49d6692018-06-27 07:17:41 +08002940 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002941 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2942 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002943 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002944 }
2945
Chia-I Wud49d6692018-06-27 07:17:41 +08002946 // The current enhanced saturation matrix is designed to enhance Display P3,
2947 // thus we only apply this matrix when the render intent is not colorimetric
2948 // and the output color space is Display P3.
2949 needsEnhancedColorMatrix =
2950 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2951 outputDataspace == Dataspace::DISPLAY_P3);
2952 if (needsEnhancedColorMatrix) {
2953 colorMatrix *= mEnhancedSaturationMatrix;
2954 }
2955
2956 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002957
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002958 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002959 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002960 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002961 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002962
2963 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002964 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2965 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2966 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002967 }
2968 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002969 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002970
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002971 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002972 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002973 // when using overlays, we assume a fully transparent framebuffer
2974 // NOTE: we could reduce how much we need to clear, for instance
2975 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002976 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002977 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002978 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002979 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002980 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002981 // we're left with the letterbox region
2982 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002983 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002984
2985 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002986 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002987
Mathias Agopianb9494d52012-04-18 02:28:45 -07002988 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002989 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002990 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002991 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002992 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002993 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002994
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002995 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002996 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002997 // scissor on the main display. It should never be needed
2998 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002999 const Rect& bounds = display->getBounds();
3000 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07003001 if (scissor != bounds) {
3002 // scissor doesn't match the screen's dimensions, so we
3003 // need to clear everything outside of it and enable
3004 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003005
Mathias Agopianf45c5102012-10-24 16:29:17 -07003006 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003007 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003008 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003009 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003010 }
3011 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003012 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003013
Mathias Agopian85d751c2012-08-29 16:59:24 -07003014 /*
3015 * and then, render the layers targeted at the framebuffer
3016 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003017
Dan Stoza9e56aa02015-11-02 13:00:03 -08003018 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003019 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003020 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003021 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003022 const Region clip(bounds.intersect(
3023 displayTransform.transform(layer->visibleRegion)));
3024 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003025 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003026 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003027 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003028 case HWC2::Composition::Cursor:
3029 case HWC2::Composition::Device:
3030 case HWC2::Composition::Sideband:
3031 case HWC2::Composition::SolidColor: {
3032 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003033 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3034 layer->isOpaque(state) && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003035 // never clear the very first layer since we're
3036 // guaranteed the FB is already cleared
3037 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003038 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003039 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003040 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003041 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003042 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003043 break;
3044 }
3045 default:
3046 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003047 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003048 } else {
3049 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003050 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003051 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003052 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003053
Chia-I Wud49d6692018-06-27 07:17:41 +08003054 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003055 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003056 }
3057
Mathias Agopianf45c5102012-10-24 16:29:17 -07003058 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003059 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003060 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003061}
3062
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003063void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3064 const Region& region) const {
3065 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003066 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003067 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068}
3069
Dan Stoza7d89d062015-04-30 13:29:25 -07003070status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003071 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003072 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003073 const sp<Layer>& lbc,
3074 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003075{
Dan Stoza7d89d062015-04-30 13:29:25 -07003076 // add this layer to the current state list
3077 {
3078 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003079 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003080 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3081 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003082 return NO_MEMORY;
3083 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003084 if (parent == nullptr) {
3085 mCurrentState.layersSortedByZ.add(lbc);
3086 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003087 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003088 ALOGE("addClientLayer called with a removed parent");
3089 return NAME_NOT_FOUND;
3090 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003091 parent->addChild(lbc);
3092 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003093
Yiwei Zhang243b3782018-05-15 17:40:04 -07003094 if (gbc != nullptr) {
3095 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3096 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3097 mMaxGraphicBufferProducerListSize,
3098 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3099 mGraphicBufferProducerList.size(),
3100 mMaxGraphicBufferProducerListSize, mNumLayers);
3101 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003102 mLayersAdded = true;
3103 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003104 }
3105
Mathias Agopian96f08192010-06-02 23:28:45 -07003106 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003107 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003108
Dan Stoza7d89d062015-04-30 13:29:25 -07003109 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003110}
3111
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003112status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003113 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003114 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3115}
Robert Carr7f9b8992017-03-10 11:08:39 -08003116
chaviwca27f252018-02-06 16:46:39 -08003117status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3118 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003119 if (layer->isPendingRemoval()) {
3120 return NO_ERROR;
3121 }
3122
Robert Carr1f0a16a2016-10-24 16:27:39 -07003123 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003124 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003125 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003126 if (topLevelOnly) {
3127 return NO_ERROR;
3128 }
3129
Chia-I Wu98f1c102017-05-30 14:54:08 -07003130 sp<Layer> ancestor = p;
3131 while (ancestor->getParent() != nullptr) {
3132 ancestor = ancestor->getParent();
3133 }
3134 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3135 ALOGE("removeLayer called with a layer whose parent has been removed");
3136 return NAME_NOT_FOUND;
3137 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003138
3139 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003140 } else {
3141 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003142 }
3143
Robert Carr136e2f62017-02-08 17:54:29 -08003144 // As a matter of normal operation, the LayerCleaner will produce a second
3145 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3146 // so we will succeed in promoting it, but it's already been removed
3147 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3148 // otherwise something has gone wrong and we are leaking the layer.
3149 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003150 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3151 layer->getName().string(),
3152 (p != nullptr) ? p->getName().string() : "no-parent");
3153 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003154 } else if (index < 0) {
3155 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003156 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003157
Chia-I Wuc6657022017-08-15 11:18:17 -07003158 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003159 mLayersPendingRemoval.add(layer);
3160 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003161 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003162 setTransactionFlags(eTransactionNeeded);
3163 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164}
3165
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003166uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003167 return android_atomic_release_load(&mTransactionFlags);
3168}
3169
Mathias Agopian3f844832013-08-07 21:24:32 -07003170uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3172}
3173
Mathias Agopian3f844832013-08-07 21:24:32 -07003174uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003175 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3176}
3177
3178uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3179 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003181 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003182 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003183 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184 }
3185 return old;
3186}
3187
chaviwca27f252018-02-06 16:46:39 -08003188bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3189 for (const ComposerState& state : states) {
3190 // Here we need to check that the interface we're given is indeed
3191 // one of our own. A malicious client could give us a nullptr
3192 // IInterface, or one of its own or even one of our own but a
3193 // different type. All these situations would cause us to crash.
3194 if (state.client == nullptr) {
3195 return true;
3196 }
3197
3198 sp<IBinder> binder = IInterface::asBinder(state.client);
3199 if (binder == nullptr) {
3200 return true;
3201 }
3202
3203 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3204 return true;
3205 }
3206 }
3207 return false;
3208}
3209
Mathias Agopian8b33f032012-07-24 20:43:54 -07003210void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003211 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003212 const Vector<DisplayState>& displays,
3213 uint32_t flags)
3214{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003215 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003216 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003217 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003218
chaviwca27f252018-02-06 16:46:39 -08003219 if (containsAnyInvalidClientState(states)) {
3220 return;
3221 }
3222
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003223 if (flags & eAnimation) {
3224 // For window updates that are part of an animation we must wait for
3225 // previous animation "frames" to be handled.
3226 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003227 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003228 if (CC_UNLIKELY(err != NO_ERROR)) {
3229 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003230 // caller after a few seconds.
3231 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3232 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003233 mAnimTransactionPending = false;
3234 break;
3235 }
3236 }
3237 }
3238
chaviwca27f252018-02-06 16:46:39 -08003239 for (const DisplayState& display : displays) {
3240 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003241 }
3242
chaviwca27f252018-02-06 16:46:39 -08003243 for (const ComposerState& state : states) {
3244 transactionFlags |= setClientStateLocked(state);
3245 }
3246
3247 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3248 // as destroyed should only occur after setting all other states. This is to allow for a
3249 // child re-parent to happen before marking its original parent as destroyed (which would
3250 // then mark the child as destroyed).
3251 for (const ComposerState& state : states) {
3252 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003253 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003254
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003255 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3256 // anyway. This can be used as a flush mechanism for previous async transactions.
3257 // Empty animation transaction can be used to simulate back-pressure, so also force a
3258 // transaction for empty animation transactions.
3259 if (transactionFlags == 0 &&
3260 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003261 transactionFlags = eTransactionNeeded;
3262 }
3263
Mathias Agopian386aa982011-11-07 21:58:03 -08003264 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003265 if (mInterceptor->isEnabled()) {
3266 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003267 }
Irvel468051e2016-06-13 16:44:44 -07003268
Mathias Agopian386aa982011-11-07 21:58:03 -08003269 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003270 const auto start = (flags & eEarlyWakeup)
3271 ? VSyncModulator::TransactionStart::EARLY
3272 : VSyncModulator::TransactionStart::NORMAL;
3273 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003274
3275 // if this is a synchronous transaction, wait for it to take effect
3276 // before returning.
3277 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003278 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003279 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003280 if (flags & eAnimation) {
3281 mAnimTransactionPending = true;
3282 }
3283 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003284 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3285 if (CC_UNLIKELY(err != NO_ERROR)) {
3286 // just in case something goes wrong in SF, return to the
3287 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003288 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3289 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003290 break;
3291 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003292 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003293 }
3294}
3295
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003296uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3297 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3298 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003299
Mathias Agopiane57f2922012-08-09 16:29:12 -07003300 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003301 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3302
3303 const uint32_t what = s.what;
3304 if (what & DisplayState::eSurfaceChanged) {
3305 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3306 state.surface = s.surface;
3307 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003308 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003309 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003310 if (what & DisplayState::eLayerStackChanged) {
3311 if (state.layerStack != s.layerStack) {
3312 state.layerStack = s.layerStack;
3313 flags |= eDisplayTransactionNeeded;
3314 }
3315 }
3316 if (what & DisplayState::eDisplayProjectionChanged) {
3317 if (state.orientation != s.orientation) {
3318 state.orientation = s.orientation;
3319 flags |= eDisplayTransactionNeeded;
3320 }
3321 if (state.frame != s.frame) {
3322 state.frame = s.frame;
3323 flags |= eDisplayTransactionNeeded;
3324 }
3325 if (state.viewport != s.viewport) {
3326 state.viewport = s.viewport;
3327 flags |= eDisplayTransactionNeeded;
3328 }
3329 }
3330 if (what & DisplayState::eDisplaySizeChanged) {
3331 if (state.width != s.width) {
3332 state.width = s.width;
3333 flags |= eDisplayTransactionNeeded;
3334 }
3335 if (state.height != s.height) {
3336 state.height = s.height;
3337 flags |= eDisplayTransactionNeeded;
3338 }
3339 }
3340
Mathias Agopiane57f2922012-08-09 16:29:12 -07003341 return flags;
3342}
3343
Robert Carrd4ae7f32018-06-07 16:10:57 -07003344bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3345 IPCThreadState* ipc = IPCThreadState::self();
3346 const int pid = ipc->getCallingPid();
3347 const int uid = ipc->getCallingUid();
3348
3349 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3350 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3351 return false;
3352 }
3353 return true;
3354}
3355
chaviwca27f252018-02-06 16:46:39 -08003356uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3357 const layer_state_t& s = composerState.state;
3358 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3359
Mathias Agopian13127d82013-03-05 17:47:11 -08003360 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003361 if (layer == nullptr) {
3362 return 0;
3363 }
3364
3365 if (layer->isPendingRemoval()) {
3366 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3367 return 0;
3368 }
3369
3370 uint32_t flags = 0;
3371
3372 const uint32_t what = s.what;
3373 bool geometryAppliesWithResize =
3374 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003375
3376 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3377 // pending state will also be deferred.
3378 if (what & layer_state_t::eDeferTransaction) {
3379 layer->pushPendingState();
3380 }
3381
chaviw8b3871a2017-11-01 17:41:01 -07003382 if (what & layer_state_t::ePositionChanged) {
3383 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3384 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003385 }
chaviw8b3871a2017-11-01 17:41:01 -07003386 }
3387 if (what & layer_state_t::eLayerChanged) {
3388 // NOTE: index needs to be calculated before we update the state
3389 const auto& p = layer->getParent();
3390 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003391 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003392 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003393 mCurrentState.layersSortedByZ.removeAt(idx);
3394 mCurrentState.layersSortedByZ.add(layer);
3395 // we need traversal (state changed)
3396 // AND transaction (list changed)
3397 flags |= eTransactionNeeded|eTraversalNeeded;
3398 }
chaviw8b3871a2017-11-01 17:41:01 -07003399 } else {
3400 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003401 flags |= eTransactionNeeded|eTraversalNeeded;
3402 }
3403 }
chaviw8b3871a2017-11-01 17:41:01 -07003404 }
3405 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003406 // NOTE: index needs to be calculated before we update the state
3407 const auto& p = layer->getParent();
3408 if (p == nullptr) {
3409 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3410 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3411 mCurrentState.layersSortedByZ.removeAt(idx);
3412 mCurrentState.layersSortedByZ.add(layer);
3413 // we need traversal (state changed)
3414 // AND transaction (list changed)
3415 flags |= eTransactionNeeded|eTraversalNeeded;
3416 }
3417 } else {
3418 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3419 flags |= eTransactionNeeded|eTraversalNeeded;
3420 }
chaviw8b3871a2017-11-01 17:41:01 -07003421 }
3422 }
3423 if (what & layer_state_t::eSizeChanged) {
3424 if (layer->setSize(s.w, s.h)) {
3425 flags |= eTraversalNeeded;
3426 }
3427 }
3428 if (what & layer_state_t::eAlphaChanged) {
3429 if (layer->setAlpha(s.alpha))
3430 flags |= eTraversalNeeded;
3431 }
3432 if (what & layer_state_t::eColorChanged) {
3433 if (layer->setColor(s.color))
3434 flags |= eTraversalNeeded;
3435 }
3436 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003437 // TODO: b/109894387
3438 //
3439 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3440 // rotation. To see the problem observe that if we have a square parent, and a child
3441 // of the same size, then we rotate the child 45 degrees around it's center, the child
3442 // must now be cropped to a non rectangular 8 sided region.
3443 //
3444 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3445 // private API, and the WindowManager only uses rotation in one case, which is on a top
3446 // level layer in which cropping is not an issue.
3447 //
3448 // However given that abuse of rotation matrices could lead to surfaces extending outside
3449 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3450 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3451 // transformations.
3452 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003453 flags |= eTraversalNeeded;
3454 }
3455 if (what & layer_state_t::eTransparentRegionChanged) {
3456 if (layer->setTransparentRegionHint(s.transparentRegion))
3457 flags |= eTraversalNeeded;
3458 }
3459 if (what & layer_state_t::eFlagsChanged) {
3460 if (layer->setFlags(s.flags, s.mask))
3461 flags |= eTraversalNeeded;
3462 }
3463 if (what & layer_state_t::eCropChanged) {
3464 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3465 flags |= eTraversalNeeded;
3466 }
3467 if (what & layer_state_t::eFinalCropChanged) {
3468 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3469 flags |= eTraversalNeeded;
3470 }
3471 if (what & layer_state_t::eLayerStackChanged) {
3472 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3473 // We only allow setting layer stacks for top level layers,
3474 // everything else inherits layer stack from its parent.
3475 if (layer->hasParent()) {
3476 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3477 layer->getName().string());
3478 } else if (idx < 0) {
3479 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3480 "that also does not appear in the top level layer list. Something"
3481 " has gone wrong.", layer->getName().string());
3482 } else if (layer->setLayerStack(s.layerStack)) {
3483 mCurrentState.layersSortedByZ.removeAt(idx);
3484 mCurrentState.layersSortedByZ.add(layer);
3485 // we need traversal (state changed)
3486 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003487 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003488 }
3489 }
3490 if (what & layer_state_t::eDeferTransaction) {
3491 if (s.barrierHandle != nullptr) {
3492 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3493 } else if (s.barrierGbp != nullptr) {
3494 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3495 if (authenticateSurfaceTextureLocked(gbp)) {
3496 const auto& otherLayer =
3497 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3498 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3499 } else {
3500 ALOGE("Attempt to defer transaction to to an"
3501 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003502 }
3503 }
chaviw8b3871a2017-11-01 17:41:01 -07003504 // We don't trigger a traversal here because if no other state is
3505 // changed, we don't want this to cause any more work
3506 }
3507 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003508 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003509 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003510 if (!hadParent) {
3511 mCurrentState.layersSortedByZ.remove(layer);
3512 }
chaviw8b3871a2017-11-01 17:41:01 -07003513 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003514 }
chaviw8b3871a2017-11-01 17:41:01 -07003515 }
3516 if (what & layer_state_t::eReparentChildren) {
3517 if (layer->reparentChildren(s.reparentHandle)) {
3518 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003519 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003520 }
chaviw8b3871a2017-11-01 17:41:01 -07003521 if (what & layer_state_t::eDetachChildren) {
3522 layer->detachChildren();
3523 }
3524 if (what & layer_state_t::eOverrideScalingModeChanged) {
3525 layer->setOverrideScalingMode(s.overrideScalingMode);
3526 // We don't trigger a traversal here because if no other state is
3527 // changed, we don't want this to cause any more work
3528 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003529 return flags;
3530}
3531
chaviwca27f252018-02-06 16:46:39 -08003532void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3533 const layer_state_t& state = composerState.state;
3534 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3535
3536 sp<Layer> layer(client->getLayerUser(state.surface));
3537 if (layer == nullptr) {
3538 return;
3539 }
3540
3541 if (layer->isPendingRemoval()) {
3542 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3543 return;
3544 }
3545
3546 if (state.what & layer_state_t::eDestroySurface) {
3547 removeLayerLocked(mStateLock, layer);
3548 }
3549}
3550
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003551status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003552 const String8& name,
3553 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003554 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003555 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003556 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003557{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003558 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003559 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003560 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003561 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003562 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003563
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003564 status_t result = NO_ERROR;
3565
3566 sp<Layer> layer;
3567
Cody Northropbc755282017-03-31 12:00:08 -06003568 String8 uniqueName = getUniqueLayerName(name);
3569
Mathias Agopian3165cc22012-08-08 19:42:09 -07003570 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3571 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003572 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003573 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003574 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003575
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576 break;
chaviw13fdc492017-06-27 12:40:18 -07003577 case ISurfaceComposerClient::eFXSurfaceColor:
3578 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003579 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003580 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003581 break;
3582 default:
3583 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003584 break;
3585 }
3586
Dan Stoza7d89d062015-04-30 13:29:25 -07003587 if (result != NO_ERROR) {
3588 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003589 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003590
Chia-I Wuab0c3192017-08-01 11:29:00 -07003591 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3592 // TODO b/64227542
3593 if (windowType == 441731) {
3594 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3595 layer->setPrimaryDisplayOnly();
3596 }
3597
Albert Chaulk479c60c2017-01-27 14:21:34 -05003598 layer->setInfo(windowType, ownerUid);
3599
Robert Carr1f0a16a2016-10-24 16:27:39 -07003600 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003601 if (result != NO_ERROR) {
3602 return result;
3603 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003604 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003605
3606 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003607 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003608}
3609
Cody Northropbc755282017-03-31 12:00:08 -06003610String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3611{
3612 bool matchFound = true;
3613 uint32_t dupeCounter = 0;
3614
3615 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3616 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3617
Dan Stoza436ccf32018-06-21 12:10:12 -07003618 // Grab the state lock since we're accessing mCurrentState
3619 Mutex::Autolock lock(mStateLock);
3620
Cody Northropbc755282017-03-31 12:00:08 -06003621 // Loop over layers until we're sure there is no matching name
3622 while (matchFound) {
3623 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003624 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003625 if (layer->getName() == uniqueName) {
3626 matchFound = true;
3627 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3628 }
3629 });
3630 }
3631
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003632 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3633 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003634
3635 return uniqueName;
3636}
3637
David Sodman0c69cad2017-08-21 12:12:51 -07003638status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003639 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3640 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003641{
3642 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003643 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003644 case PIXEL_FORMAT_TRANSPARENT:
3645 case PIXEL_FORMAT_TRANSLUCENT:
3646 format = PIXEL_FORMAT_RGBA_8888;
3647 break;
3648 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003649 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003650 break;
3651 }
3652
David Sodman0c69cad2017-08-21 12:12:51 -07003653 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3654 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003655 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003656 *handle = layer->getHandle();
3657 *gbp = layer->getProducer();
3658 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003659 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003660
David Sodman0c69cad2017-08-21 12:12:51 -07003661 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003662 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003663}
3664
chaviw13fdc492017-06-27 12:40:18 -07003665status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003666 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003667 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003668{
chaviw13fdc492017-06-27 12:40:18 -07003669 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003670 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003671 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003672}
3673
Mathias Agopianac9fa422013-02-11 16:40:36 -08003674status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003675{
Robert Carr9524cb32017-02-13 11:32:32 -08003676 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003677 status_t err = NO_ERROR;
3678 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003679 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003680 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003681 err = removeLayer(l);
3682 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3683 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003684 }
3685 return err;
3686}
3687
Mathias Agopian13127d82013-03-05 17:47:11 -08003688status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003689{
Mathias Agopian67106042013-03-14 19:18:13 -07003690 // called by ~LayerCleaner() when all references to the IBinder (handle)
3691 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003692 sp<Layer> l = layer.promote();
3693 if (l == nullptr) {
3694 // The layer has already been removed, carry on
3695 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003696 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003697 // If we have a parent, then we can continue to live as long as it does.
3698 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003699}
3700
Mathias Agopianb60314a2012-04-10 22:09:54 -07003701// ---------------------------------------------------------------------------
3702
Andy McFadden13a082e2012-08-24 10:16:42 -07003703void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003704 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3705 if (!displayToken) return;
3706
Jesse Hall01e29052013-02-19 16:13:35 -08003707 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003708 Vector<ComposerState> state;
3709 Vector<DisplayState> displays;
3710 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003711 d.what = DisplayState::eDisplayProjectionChanged |
3712 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003713 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003714 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003715 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003716 d.frame.makeInvalid();
3717 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003718 d.width = 0;
3719 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003720 displays.add(d);
3721 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003722
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003723 const auto display = getDisplayDevice(displayToken);
3724 if (!display) return;
3725
3726 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3727
3728 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003729 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003730 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003731
Brian Andersond0010582017-03-07 13:20:31 -08003732 // Use phase of 0 since phase is not known.
3733 // Use latency of 0, which will snap to the ideal latency.
3734 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003735}
3736
3737void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003738 // Async since we may be called from the main thread.
3739 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003740}
3741
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003742void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3743 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003744 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003745 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003746
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003747 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003748 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003749 return;
3750 }
3751
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003752 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003753 ALOGW("Trying to set power mode for virtual display");
3754 return;
3755 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003756
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003757 display->setPowerMode(mode);
3758
Lloyd Pique4dccc412018-01-22 17:21:36 -08003759 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003760 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003761 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003762 if (idx < 0) {
3763 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3764 return;
3765 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003766 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003767 }
3768
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003769 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003770 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003771 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003772 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003773 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003774 // FIXME: eventthread only knows about the main display right now
3775 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003776 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003777 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003778
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003779 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003780 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003781 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003782
3783 struct sched_param param = {0};
3784 param.sched_priority = 1;
3785 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3786 ALOGW("Couldn't set SCHED_FIFO on display on");
3787 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003788 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003789 // Turn off the display
3790 struct sched_param param = {0};
3791 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3792 ALOGW("Couldn't set SCHED_OTHER on display off");
3793 }
3794
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003795 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003796 disableHardwareVsync(true); // also cancels any in-progress resync
3797
Mathias Agopiancde87a32012-09-13 14:09:01 -07003798 // FIXME: eventthread only knows about the main display right now
3799 mEventThread->onScreenReleased();
3800 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003801
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003802 getHwComposer().setPowerMode(type, mode);
3803 mVisibleRegionsDirty = true;
3804 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003805 } else if (mode == HWC_POWER_MODE_DOZE ||
3806 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003807 // Update display while dozing
3808 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003809 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003810 // FIXME: eventthread only knows about the main display right now
3811 mEventThread->onScreenAcquired();
3812 resyncToHardwareVsync(true);
3813 }
3814 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3815 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003816 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003817 disableHardwareVsync(true); // also cancels any in-progress resync
3818 // FIXME: eventthread only knows about the main display right now
3819 mEventThread->onScreenReleased();
3820 }
3821 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003822 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003823 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003824 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003825 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003826
3827 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003828}
3829
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003830void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003831 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003832 const auto display = getDisplayDevice(displayToken);
3833 if (!display) {
3834 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3835 displayToken.get());
3836 } else if (display->isVirtual()) {
3837 ALOGW("Attempt to set power mode %d for virtual display", mode);
3838 } else {
3839 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003840 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003841 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003842}
3843
3844// ---------------------------------------------------------------------------
3845
Lloyd Pique755e3192018-01-31 16:46:15 -08003846status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3847 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003848 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003849
Mathias Agopianbd115332013-04-18 16:41:04 -07003850 IPCThreadState* ipc = IPCThreadState::self();
3851 const int pid = ipc->getCallingPid();
3852 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003853
Mathias Agopianbd115332013-04-18 16:41:04 -07003854 if ((uid != AID_SHELL) &&
3855 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003856 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003857 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003858 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003859 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003860 // (this would indicate SF is stuck, but we want to be able to
3861 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003862 status_t err = mStateLock.timedLock(s2ns(1));
3863 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003864 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003865 result.appendFormat(
3866 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3867 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003868 }
3869
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003870 bool dumpAll = true;
3871 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003872 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003873
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003874 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003875 if ((index < numArgs) &&
3876 (args[index] == String16("--list"))) {
3877 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003878 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003879 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003880 }
3881
3882 if ((index < numArgs) &&
3883 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003884 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003885 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003886 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003887 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003888
3889 if ((index < numArgs) &&
3890 (args[index] == String16("--latency-clear"))) {
3891 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003892 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003893 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003894 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003895
3896 if ((index < numArgs) &&
3897 (args[index] == String16("--dispsync"))) {
3898 index++;
3899 mPrimaryDispSync.dump(result);
3900 dumpAll = false;
3901 }
Dan Stozab90cf072015-03-05 11:05:59 -08003902
3903 if ((index < numArgs) &&
3904 (args[index] == String16("--static-screen"))) {
3905 index++;
3906 dumpStaticScreenStats(result);
3907 dumpAll = false;
3908 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003909
3910 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003911 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003912 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003913 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003914 dumpAll = false;
3915 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003916
3917 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3918 index++;
3919 dumpWideColorInfo(result);
3920 dumpAll = false;
3921 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003922
3923 if ((index < numArgs) &&
3924 (args[index] == String16("--enable-layer-stats"))) {
3925 index++;
3926 mLayerStats.enable();
3927 dumpAll = false;
3928 }
3929
3930 if ((index < numArgs) &&
3931 (args[index] == String16("--disable-layer-stats"))) {
3932 index++;
3933 mLayerStats.disable();
3934 dumpAll = false;
3935 }
3936
3937 if ((index < numArgs) &&
3938 (args[index] == String16("--clear-layer-stats"))) {
3939 index++;
3940 mLayerStats.clear();
3941 dumpAll = false;
3942 }
3943
3944 if ((index < numArgs) &&
3945 (args[index] == String16("--dump-layer-stats"))) {
3946 index++;
3947 mLayerStats.dump(result);
3948 dumpAll = false;
3949 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003950
3951 if ((index < numArgs) &&
3952 (args[index] == String16("--display-identification"))) {
3953 index++;
3954 dumpDisplayIdentificationData(result);
3955 dumpAll = false;
3956 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003957
3958 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3959 index++;
3960 mTimeStats.parseArgs(asProto, args, index, result);
3961 dumpAll = false;
3962 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003963 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003964
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003965 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003966 if (asProto) {
3967 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3968 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3969 } else {
3970 dumpAllLocked(args, index, result);
3971 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003972 }
3973
Mathias Agopian9795c422009-08-26 16:36:26 -07003974 if (locked) {
3975 mStateLock.unlock();
3976 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003977 }
3978 write(fd, result.string(), result.size());
3979 return NO_ERROR;
3980}
3981
Dan Stozac7014012014-02-14 15:03:43 -08003982void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3983 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003984{
Robert Carr2047fae2016-11-28 14:09:09 -08003985 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003986 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003987 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003988}
3989
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003990void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003991 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003992{
3993 String8 name;
3994 if (index < args.size()) {
3995 name = String8(args[index]);
3996 index++;
3997 }
3998
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003999 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4000 getHwComposer().isConnected(displayId)) {
4001 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4002 const nsecs_t period = activeConfig->getVsyncPeriod();
4003 result.appendFormat("%" PRId64 "\n", period);
4004 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004005
4006 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004007 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004008 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004009 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004010 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004011 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004012 }
Robert Carr2047fae2016-11-28 14:09:09 -08004013 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004014 }
4015}
4016
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004017void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004018 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004019{
4020 String8 name;
4021 if (index < args.size()) {
4022 name = String8(args[index]);
4023 index++;
4024 }
4025
Robert Carr2047fae2016-11-28 14:09:09 -08004026 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004027 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004028 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004029 }
Robert Carr2047fae2016-11-28 14:09:09 -08004030 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004031
Svetoslavd85084b2014-03-20 10:28:31 -07004032 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004033}
4034
Jamie Gennis6547ff42013-07-16 20:12:42 -07004035// This should only be called from the main thread. Otherwise it would need
4036// the lock and should use mCurrentState rather than mDrawingState.
4037void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004038 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004039 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004040 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004041
4042 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4043}
4044
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004045void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004046{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004047 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004048
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004049 if (isLayerTripleBufferingDisabled())
4050 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004051
4052 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004053 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004054 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004055 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004056 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4057 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004058 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004059}
4060
Dan Stozab90cf072015-03-05 11:05:59 -08004061void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4062{
4063 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004064 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4065 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004066 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004067 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004068 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4069 b + 1, bucketTimeSec, percent);
4070 }
David Sodman4a36e932017-11-07 14:29:47 -08004071 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004072 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004073 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004074 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004075 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004076}
4077
Dan Stozae77c7662016-05-13 11:37:28 -07004078void SurfaceFlinger::recordBufferingStats(const char* layerName,
4079 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004080 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4081 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004082 for (const auto& segment : history) {
4083 if (!segment.usedThirdBuffer) {
4084 stats.twoBufferTime += segment.totalTime;
4085 }
4086 if (segment.occupancyAverage < 1.0f) {
4087 stats.doubleBufferedTime += segment.totalTime;
4088 } else if (segment.occupancyAverage < 2.0f) {
4089 stats.tripleBufferedTime += segment.totalTime;
4090 }
4091 ++stats.numSegments;
4092 stats.totalTime += segment.totalTime;
4093 }
4094}
4095
Brian Andersond6927fb2016-07-23 23:37:30 -07004096void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4097 result.appendFormat("Layer frame timestamps:\n");
4098
4099 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4100 const size_t count = currentLayers.size();
4101 for (size_t i=0 ; i<count ; i++) {
4102 currentLayers[i]->dumpFrameEvents(result);
4103 }
4104}
4105
Dan Stozae77c7662016-05-13 11:37:28 -07004106void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4107 result.append("Buffering stats:\n");
4108 result.append(" [Layer name] <Active time> <Two buffer> "
4109 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004110 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004111 typedef std::tuple<std::string, float, float, float> BufferTuple;
4112 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004113 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004114 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004115 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004116 if (stats.numSegments == 0) {
4117 continue;
4118 }
4119 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4120 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4121 stats.totalTime;
4122 float doubleBufferRatio = static_cast<float>(
4123 stats.doubleBufferedTime) / stats.totalTime;
4124 float tripleBufferRatio = static_cast<float>(
4125 stats.tripleBufferedTime) / stats.totalTime;
4126 sorted.insert({activeTime, {name, twoBufferRatio,
4127 doubleBufferRatio, tripleBufferRatio}});
4128 }
4129 for (const auto& sortedPair : sorted) {
4130 float activeTime = sortedPair.first;
4131 const BufferTuple& values = sortedPair.second;
4132 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4133 std::get<0>(values).c_str(), activeTime,
4134 std::get<1>(values), std::get<2>(values),
4135 std::get<3>(values));
4136 }
4137 result.append("\n");
4138}
4139
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004140void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004141 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004142 const int32_t displayId = display->getId();
4143 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4144 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004145 continue;
4146 }
4147
Dominik Laskowski7e045462018-05-30 13:02:02 -07004148 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004149 uint8_t port;
4150 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004151 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004152 result.append("no identification data\n");
4153 continue;
4154 }
4155
4156 if (!isEdid(data)) {
4157 result.append("unknown identification data: ");
4158 for (uint8_t byte : data) {
4159 result.appendFormat("%x ", byte);
4160 }
4161 result.append("\n");
4162 continue;
4163 }
4164
4165 const auto edid = parseEdid(data);
4166 if (!edid) {
4167 result.append("invalid EDID: ");
4168 for (uint8_t byte : data) {
4169 result.appendFormat("%x ", byte);
4170 }
4171 result.append("\n");
4172 continue;
4173 }
4174
4175 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4176 result.append(edid->displayName.data(), edid->displayName.length());
4177 result.append("\"\n");
4178 }
4179 result.append("\n");
4180}
4181
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004182void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4183 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004184 result.appendFormat("DisplayColorSetting: %s\n",
4185 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004186
4187 // TODO: print out if wide-color mode is active or not
4188
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004189 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004190 const int32_t displayId = display->getId();
4191 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004192 continue;
4193 }
4194
Dominik Laskowski7e045462018-05-30 13:02:02 -07004195 result.appendFormat("Display %d color modes:\n", displayId);
4196 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004197 for (auto&& mode : modes) {
4198 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4199 }
4200
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004201 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004202 result.appendFormat(" Current color mode: %s (%d)\n",
4203 decodeColorMode(currentMode).c_str(), currentMode);
4204 }
4205 result.append("\n");
4206}
4207
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004208LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004209 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004210 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4211 const State& state = useDrawing ? mDrawingState : mCurrentState;
4212 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004213 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004214 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004215 });
4216
4217 return layersProto;
4218}
4219
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004220LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004221 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004222
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004223 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004224 resolution->set_w(display.getWidth());
4225 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004226
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004227 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4228 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4229 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004230
Dominik Laskowski7e045462018-05-30 13:02:02 -07004231 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004232 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004233 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004234 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004235 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004236 }
4237 });
4238
4239 return layersProto;
4240}
4241
Mathias Agopian74d211a2013-04-22 16:55:35 +02004242void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4243 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004244{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004245 bool colorize = false;
4246 if (index < args.size()
4247 && (args[index] == String16("--color"))) {
4248 colorize = true;
4249 index++;
4250 }
4251
4252 Colorizer colorizer(colorize);
4253
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004254 // figure out if we're stuck somewhere
4255 const nsecs_t now = systemTime();
4256 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4257 const nsecs_t inTransaction(mDebugInTransaction);
4258 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4259 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4260
4261 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004262 * Dump library configuration.
4263 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004264
4265 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004266 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004267 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004268 appendSfConfigString(result);
4269 appendUiConfigString(result);
4270 appendGuiConfigString(result);
4271 result.append("\n");
4272
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004273 result.append("\nDisplay identification data:\n");
4274 dumpDisplayIdentificationData(result);
4275
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004276 result.append("\nWide-Color information:\n");
4277 dumpWideColorInfo(result);
4278
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004279 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004280 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004281 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004282 result.append(SyncFeatures::getInstance().toString());
4283 result.append("\n");
4284
Andy McFadden41d67d72014-04-25 16:58:34 -07004285 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004286 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004287 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004288
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004289 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4290 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004291 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4292 getHwComposer().isConnected(displayId)) {
4293 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004294 result.appendFormat("Display %d: "
4295 "app phase %" PRId64 " ns, "
4296 "sf phase %" PRId64 " ns, "
4297 "early app phase %" PRId64 " ns, "
4298 "early sf phase %" PRId64 " ns, "
4299 "early app gl phase %" PRId64 " ns, "
4300 "early sf gl phase %" PRId64 " ns, "
4301 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4302 displayId,
4303 vsyncPhaseOffsetNs,
4304 sfVsyncPhaseOffsetNs,
4305 appEarlyOffset,
4306 sfEarlyOffset,
4307 appEarlyGlOffset,
4308 sfEarlyOffset,
4309 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004310 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004311 result.append("\n");
4312
Dan Stozab90cf072015-03-05 11:05:59 -08004313 // Dump static screen stats
4314 result.append("\n");
4315 dumpStaticScreenStats(result);
4316 result.append("\n");
4317
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004318 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4319
Dan Stozae77c7662016-05-13 11:37:28 -07004320 dumpBufferingStats(result);
4321
Andy McFadden4803b742012-09-24 19:07:20 -07004322 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004323 * Dump the visible layer list
4324 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004325 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004326 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004327 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4328 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004329 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004330
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004331 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004332 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004333 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004334 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004335
4336 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004337 * Dump Display state
4338 */
4339
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004340 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004341 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004342 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004343 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004344 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004345 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004346 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004347
4348 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004349 * Dump SurfaceFlinger global state
4350 */
4351
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004352 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004353 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004354 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004355
Mathias Agopian888c8222012-08-04 21:10:38 -07004356 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004357 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004358
David Sodmanbc815282017-11-05 18:57:52 -08004359 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004360
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004361 if (display) {
4362 display->undefinedRegion.dump(result, "undefinedRegion");
4363 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4364 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004365 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004366 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4367 " last transaction time : %f us\n"
4368 " transaction-flags : %08x\n"
4369 " gpu_to_cpu_unsupported : %d\n",
4370 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4371 mTransactionFlags, !mGpuToCpuSupported);
4372
4373 if (display) {
4374 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4375 result.appendFormat(" refresh-rate : %f fps\n"
4376 " x-dpi : %f\n"
4377 " y-dpi : %f\n",
4378 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4379 activeConfig->getDpiY());
4380 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004381
Mathias Agopian74d211a2013-04-22 16:55:35 +02004382 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004383 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004384
Mathias Agopian74d211a2013-04-22 16:55:35 +02004385 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004386 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004387
4388 /*
4389 * VSYNC state
4390 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004391 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004392 result.append("\n");
4393
4394 /*
4395 * HWC layer minidump
4396 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004397 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004398 const int32_t displayId = display->getId();
4399 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004400 continue;
4401 }
4402
Dominik Laskowski7e045462018-05-30 13:02:02 -07004403 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004404 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004405 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004406 result.append("\n");
4407 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004408
4409 /*
4410 * Dump HWComposer state
4411 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004412 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004413 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004414 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004415 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004416 result.appendFormat(" h/w composer %s\n",
4417 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004418 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004419
4420 /*
4421 * Dump gralloc state
4422 */
4423 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4424 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004425
4426 /*
4427 * Dump VrFlinger state if in use.
4428 */
4429 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4430 result.append("VrFlinger state:\n");
4431 result.append(mVrFlinger->Dump().c_str());
4432 result.append("\n");
4433 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004434}
4435
Dominik Laskowski7e045462018-05-30 13:02:02 -07004436const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004437 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004438 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004439 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004440 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004441 }
4442 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004443
4444 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4445 static const Vector<sp<Layer>> empty;
4446 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004447}
4448
Keun young Park63f165f2012-08-31 10:53:36 -07004449bool SurfaceFlinger::startDdmConnection()
4450{
4451 void* libddmconnection_dso =
4452 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4453 if (!libddmconnection_dso) {
4454 return false;
4455 }
4456 void (*DdmConnection_start)(const char* name);
4457 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004458 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004459 if (!DdmConnection_start) {
4460 dlclose(libddmconnection_dso);
4461 return false;
4462 }
4463 (*DdmConnection_start)(getServiceName());
4464 return true;
4465}
4466
Chia-I Wu28f320b2018-05-03 11:02:56 -07004467void SurfaceFlinger::updateColorMatrixLocked() {
4468 mat4 colorMatrix;
4469 if (mGlobalSaturationFactor != 1.0f) {
4470 // Rec.709 luma coefficients
4471 float3 luminance{0.213f, 0.715f, 0.072f};
4472 luminance *= 1.0f - mGlobalSaturationFactor;
4473 mat4 saturationMatrix = mat4(
4474 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4475 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4476 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4477 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4478 );
4479 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4480 } else {
4481 colorMatrix = mClientColorMatrix * mDaltonizer();
4482 }
4483
4484 if (mCurrentState.colorMatrix != colorMatrix) {
4485 mCurrentState.colorMatrix = colorMatrix;
4486 mCurrentState.colorMatrixChanged = true;
4487 setTransactionFlags(eTransactionNeeded);
4488 }
4489}
4490
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004491status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004492 switch (code) {
4493 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004494 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004495 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004496 case CLEAR_ANIMATION_FRAME_STATS:
4497 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004498 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004499 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004500 case ENABLE_VSYNC_INJECTIONS:
4501 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004502 {
4503 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004504 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4505 IPCThreadState* ipc = IPCThreadState::self();
4506 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4507 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004508 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004509 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004510 break;
4511 }
Robert Carr1db73f62016-12-21 12:58:51 -08004512 /*
4513 * Calling setTransactionState is safe, because you need to have been
4514 * granted a reference to Client* and Handle* to do anything with it.
4515 *
4516 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4517 */
4518 case SET_TRANSACTION_STATE:
4519 case CREATE_SCOPED_CONNECTION:
4520 {
4521 return OK;
4522 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004523 case CAPTURE_SCREEN:
4524 {
4525 // codes that require permission check
4526 IPCThreadState* ipc = IPCThreadState::self();
4527 const int pid = ipc->getCallingPid();
4528 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004529 if ((uid != AID_GRAPHICS) &&
4530 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004531 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004532 return PERMISSION_DENIED;
4533 }
4534 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004535 }
chaviwa76b2712017-09-20 12:02:26 -07004536 case CAPTURE_LAYERS: {
4537 IPCThreadState* ipc = IPCThreadState::self();
4538 const int pid = ipc->getCallingPid();
4539 const int uid = ipc->getCallingUid();
4540 if ((uid != AID_GRAPHICS) &&
4541 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4542 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4543 return PERMISSION_DENIED;
4544 }
4545 break;
4546 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004547 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004548 return OK;
4549}
4550
4551status_t SurfaceFlinger::onTransact(
4552 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4553{
4554 status_t credentialCheck = CheckTransactCodeCredentials(code);
4555 if (credentialCheck != OK) {
4556 return credentialCheck;
4557 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004558
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004559 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4560 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004561 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004562 IPCThreadState* ipc = IPCThreadState::self();
4563 const int uid = ipc->getCallingUid();
4564 if (CC_UNLIKELY(uid != AID_SYSTEM
4565 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004566 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004567 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004568 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004569 return PERMISSION_DENIED;
4570 }
4571 int n;
4572 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004573 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004574 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004575 return NO_ERROR;
4576 case 1002: // SHOW_UPDATES
4577 n = data.readInt32();
4578 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004579 invalidateHwcGeometry();
4580 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004581 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004582 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004583 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004584 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004585 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004586 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004587 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004588 setTransactionFlags(
4589 eTransactionNeeded|
4590 eDisplayTransactionNeeded|
4591 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004592 return NO_ERROR;
4593 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004594 case 1006:{ // send empty update
4595 signalRefresh();
4596 return NO_ERROR;
4597 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004598 case 1008: // toggle use of hw composer
4599 n = data.readInt32();
4600 mDebugDisableHWC = n ? 1 : 0;
4601 invalidateHwcGeometry();
4602 repaintEverything();
4603 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004604 case 1009: // toggle use of transform hint
4605 n = data.readInt32();
4606 mDebugDisableTransformHint = n ? 1 : 0;
4607 invalidateHwcGeometry();
4608 repaintEverything();
4609 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004610 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004611 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004612 reply->writeInt32(0);
4613 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004614 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004615 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004616 return NO_ERROR;
4617 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004618 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004619 if (!display) {
4620 return NAME_NOT_FOUND;
4621 }
4622
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004623 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004624 return NO_ERROR;
4625 }
4626 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004627 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004628 // daltonize
4629 n = data.readInt32();
4630 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004631 case 1:
4632 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4633 break;
4634 case 2:
4635 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4636 break;
4637 case 3:
4638 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4639 break;
4640 default:
4641 mDaltonizer.setType(ColorBlindnessType::None);
4642 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004643 }
4644 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004645 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004646 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004647 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004648 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004649
4650 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004651 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004652 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004653 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004654 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004655 // apply a color matrix
4656 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004657 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004658 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004659 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004660 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004661 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004662 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004663 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004664 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004665 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004666 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004667
4668 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4669 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004670 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004671 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4672 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4673 }
4674
Chia-I Wu28f320b2018-05-03 11:02:56 -07004675 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004676 return NO_ERROR;
4677 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004678 // This is an experimental interface
4679 // Needs to be shifted to proper binder interface when we productize
4680 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004681 n = data.readInt32();
4682 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004683 return NO_ERROR;
4684 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004685 case 1017: {
4686 n = data.readInt32();
4687 mForceFullDamage = static_cast<bool>(n);
4688 return NO_ERROR;
4689 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004690 case 1018: { // Modify Choreographer's phase offset
4691 n = data.readInt32();
4692 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4693 return NO_ERROR;
4694 }
4695 case 1019: { // Modify SurfaceFlinger's phase offset
4696 n = data.readInt32();
4697 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4698 return NO_ERROR;
4699 }
Irvel468051e2016-06-13 16:44:44 -07004700 case 1020: { // Layer updates interceptor
4701 n = data.readInt32();
4702 if (n) {
4703 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004704 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004705 }
4706 else{
4707 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004708 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004709 }
4710 return NO_ERROR;
4711 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004712 case 1021: { // Disable HWC virtual displays
4713 n = data.readInt32();
4714 mUseHwcVirtualDisplays = !n;
4715 return NO_ERROR;
4716 }
Romain Guy0147a172017-06-01 13:53:56 -07004717 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004718 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004719 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004720
Chia-I Wu28f320b2018-05-03 11:02:56 -07004721 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004722 return NO_ERROR;
4723 }
Romain Guy54f154a2017-10-24 21:40:32 +01004724 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004725 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004726 invalidateHwcGeometry();
4727 repaintEverything();
4728 return NO_ERROR;
4729 }
4730 case 1024: { // Is wide color gamut rendering/color management supported?
4731 reply->writeBool(hasWideColorDisplay);
4732 return NO_ERROR;
4733 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004734 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004735 n = data.readInt32();
4736 if (n) {
4737 ALOGV("LayerTracing enabled");
4738 mTracing.enable();
4739 doTracing("tracing.enable");
4740 reply->writeInt32(NO_ERROR);
4741 } else {
4742 ALOGV("LayerTracing disabled");
4743 status_t err = mTracing.disable();
4744 reply->writeInt32(err);
4745 }
4746 return NO_ERROR;
4747 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004748 case 1026: { // Get layer tracing status
4749 reply->writeBool(mTracing.isEnabled());
4750 return NO_ERROR;
4751 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004752 // Is a DisplayColorSetting supported?
4753 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004754 const auto display = getDefaultDisplayDevice();
4755 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004756 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004757 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004758
4759 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4760 switch (setting) {
4761 case DisplayColorSetting::MANAGED:
4762 reply->writeBool(hasWideColorDisplay);
4763 break;
4764 case DisplayColorSetting::UNMANAGED:
4765 reply->writeBool(true);
4766 break;
4767 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004768 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004769 break;
4770 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004771 reply->writeBool(
4772 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004773 break;
4774 }
4775 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004776 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004777 // Is VrFlinger active?
4778 case 1028: {
4779 Mutex::Autolock _l(mStateLock);
4780 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4781 return NO_ERROR;
4782 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004783 }
4784 }
4785 return err;
4786}
4787
Steven Thomas6d8110b2017-08-31 18:24:21 -07004788void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004789 android_atomic_or(1, &mRepaintEverything);
4790 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004791}
4792
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004793// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4794class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004795public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004796 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4797 ~WindowDisconnector() {
4798 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004799 }
4800
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004801private:
4802 ANativeWindow* mWindow;
4803 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004804};
4805
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004806status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4807 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4808 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4809 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004810 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004811 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004812
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004813 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004814
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004815 const auto display = getDisplayDeviceLocked(displayToken);
4816 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004817
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004818 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004819
4820 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004821 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004822 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004823}
4824
4825status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004826 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004827 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004828 ATRACE_CALL();
4829
4830 class LayerRenderArea : public RenderArea {
4831 public:
Robert Carr578038f2018-03-09 12:25:24 -08004832 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4833 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004834 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004835 mLayer(layer),
4836 mCrop(crop),
4837 mFlinger(flinger),
4838 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004839 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004840 Rect getBounds() const override {
4841 const Layer::State& layerState(mLayer->getDrawingState());
4842 return Rect(layerState.active.w, layerState.active.h);
4843 }
4844 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4845 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4846 bool isSecure() const override { return false; }
4847 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004848 Rect getSourceCrop() const override {
4849 if (mCrop.isEmpty()) {
4850 return getBounds();
4851 } else {
4852 return mCrop;
4853 }
4854 }
Robert Carr578038f2018-03-09 12:25:24 -08004855 class ReparentForDrawing {
4856 public:
4857 const sp<Layer>& oldParent;
4858 const sp<Layer>& newParent;
4859
4860 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4861 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004862 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004863 }
Robert Carr15eae092018-03-23 13:43:53 -07004864 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004865 };
4866
4867 void render(std::function<void()> drawLayers) override {
4868 if (!mChildrenOnly) {
4869 mTransform = mLayer->getTransform().inverse();
4870 drawLayers();
4871 } else {
4872 Rect bounds = getBounds();
4873 screenshotParentLayer =
4874 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4875 bounds.getWidth(), bounds.getHeight(), 0);
4876
4877 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4878 drawLayers();
4879 }
4880 }
chaviwa76b2712017-09-20 12:02:26 -07004881
chaviwa76b2712017-09-20 12:02:26 -07004882 private:
chaviw7206d492017-11-10 16:16:12 -08004883 const sp<Layer> mLayer;
4884 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004885
4886 // In the "childrenOnly" case we reparent the children to a screenshot
4887 // layer which has no properties set and which does not draw.
4888 sp<ContainerLayer> screenshotParentLayer;
4889 Transform mTransform;
4890
4891 SurfaceFlinger* mFlinger;
4892 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004893 };
4894
4895 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4896 auto parent = layerHandle->owner.promote();
4897
chaviw7206d492017-11-10 16:16:12 -08004898 if (parent == nullptr || parent->isPendingRemoval()) {
4899 ALOGE("captureLayers called with a removed parent");
4900 return NAME_NOT_FOUND;
4901 }
4902
Robert Carr578038f2018-03-09 12:25:24 -08004903 const int uid = IPCThreadState::self()->getCallingUid();
4904 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4905 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4906 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4907 return PERMISSION_DENIED;
4908 }
4909
chaviw7206d492017-11-10 16:16:12 -08004910 Rect crop(sourceCrop);
4911 if (sourceCrop.width() <= 0) {
4912 crop.left = 0;
4913 crop.right = parent->getCurrentState().active.w;
4914 }
4915
4916 if (sourceCrop.height() <= 0) {
4917 crop.top = 0;
4918 crop.bottom = parent->getCurrentState().active.h;
4919 }
4920
4921 int32_t reqWidth = crop.width() * frameScale;
4922 int32_t reqHeight = crop.height() * frameScale;
4923
Robert Carr578038f2018-03-09 12:25:24 -08004924 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004925
Robert Carr578038f2018-03-09 12:25:24 -08004926 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004927 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4928 if (!layer->isVisible()) {
4929 return;
Robert Carr578038f2018-03-09 12:25:24 -08004930 } else if (childrenOnly && layer == parent.get()) {
4931 return;
chaviwa76b2712017-09-20 12:02:26 -07004932 }
4933 visitor(layer);
4934 });
4935 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004936 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004937}
4938
4939status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4940 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004941 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004942 bool useIdentityTransform) {
4943 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004944
Iris Chang7501ed62018-04-30 14:45:42 +08004945 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004946
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004947 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4948 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4949 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4950 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004951
4952 // This mutex protects syncFd and captureResult for communication of the return values from the
4953 // main thread back to this Binder thread
4954 std::mutex captureMutex;
4955 std::condition_variable captureCondition;
4956 std::unique_lock<std::mutex> captureLock(captureMutex);
4957 int syncFd = -1;
4958 std::optional<status_t> captureResult;
4959
Robert Carr03480e22018-01-04 16:02:06 -08004960 const int uid = IPCThreadState::self()->getCallingUid();
4961 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4962
Dominik Laskowski8c001672018-05-30 16:52:06 -07004963 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004964 // If there is a refresh pending, bug out early and tell the binder thread to try again
4965 // after the refresh.
4966 if (mRefreshPending) {
4967 ATRACE_NAME("Skipping screenshot for now");
4968 std::unique_lock<std::mutex> captureLock(captureMutex);
4969 captureResult = std::make_optional<status_t>(EAGAIN);
4970 captureCondition.notify_one();
4971 return;
4972 }
4973
4974 status_t result = NO_ERROR;
4975 int fd = -1;
4976 {
4977 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07004978 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08004979 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4980 useIdentityTransform, forSystem, &fd);
4981 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004982 }
4983
4984 {
4985 std::unique_lock<std::mutex> captureLock(captureMutex);
4986 syncFd = fd;
4987 captureResult = std::make_optional<status_t>(result);
4988 captureCondition.notify_one();
4989 }
4990 });
4991
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004992 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004993 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004994 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004995 while (*captureResult == EAGAIN) {
4996 captureResult.reset();
4997 result = postMessageAsync(message);
4998 if (result != NO_ERROR) {
4999 return result;
5000 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005001 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005002 }
5003 result = *captureResult;
5004 }
5005
5006 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005007 sync_wait(syncFd, -1);
5008 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005009 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005010
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005011 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005012}
5013
chaviwa76b2712017-09-20 12:02:26 -07005014void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5015 TraverseLayersFunction traverseLayers, bool yswap,
5016 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005017 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005018
Lloyd Pique144e1162017-12-20 16:44:52 -08005019 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005020
5021 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005022 const auto raWidth = renderArea.getWidth();
5023 const auto raHeight = renderArea.getHeight();
5024
5025 const auto reqWidth = renderArea.getReqWidth();
5026 const auto reqHeight = renderArea.getReqHeight();
5027 Rect sourceCrop = renderArea.getSourceCrop();
5028
Iris Chang7501ed62018-04-30 14:45:42 +08005029 bool filtering = false;
5030 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5031 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5032 static_cast<int32_t>(reqHeight) != raWidth;
5033 } else {
5034 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5035 static_cast<int32_t>(reqHeight) != raHeight;
5036 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005037
Dan Stozac1879002014-05-22 15:59:05 -07005038 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005039 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005040 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005041 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005042 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5043 Transform tr;
5044 uint32_t flags = 0x00;
5045 switch (mPrimaryDisplayOrientation) {
5046 case DisplayState::eOrientation90:
5047 flags = Transform::ROT_90;
5048 break;
5049 case DisplayState::eOrientation180:
5050 flags = Transform::ROT_180;
5051 break;
5052 case DisplayState::eOrientation270:
5053 flags = Transform::ROT_270;
5054 break;
5055 }
5056 tr.set(flags, raWidth, raHeight);
5057 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005058 }
5059
5060 // ensure that sourceCrop is inside screen
5061 if (sourceCrop.left < 0) {
5062 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5063 }
chaviwa76b2712017-09-20 12:02:26 -07005064 if (sourceCrop.right > raWidth) {
5065 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005066 }
5067 if (sourceCrop.top < 0) {
5068 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5069 }
chaviwa76b2712017-09-20 12:02:26 -07005070 if (sourceCrop.bottom > raHeight) {
5071 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005072 }
5073
Chia-I Wu36574d92018-05-16 10:54:36 -07005074 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5075 engine.setOutputDataSpace(Dataspace::SRGB);
5076 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005077
Mathias Agopian180f10d2013-04-10 22:55:41 -07005078 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005079 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005080
Iris Chang7501ed62018-04-30 14:45:42 +08005081 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5082 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5083 // convert hw orientation into flag presentation
5084 // here inverse transform needed
5085 uint8_t hw_rot_90 = 0x00;
5086 uint8_t hw_flip_hv = 0x00;
5087 switch (mPrimaryDisplayOrientation) {
5088 case DisplayState::eOrientation90:
5089 hw_rot_90 = Transform::ROT_90;
5090 hw_flip_hv = Transform::ROT_180;
5091 break;
5092 case DisplayState::eOrientation180:
5093 hw_flip_hv = Transform::ROT_180;
5094 break;
5095 case DisplayState::eOrientation270:
5096 hw_rot_90 = Transform::ROT_90;
5097 break;
5098 }
5099
5100 // transform flags operation
5101 // 1) flip H V if both have ROT_90 flag
5102 // 2) XOR these flags
5103 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5104 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5105 if (rotation_rot_90 & hw_rot_90) {
5106 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5107 }
5108 rotation = static_cast<Transform::orientation_flags>
5109 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5110 }
5111
Mathias Agopian180f10d2013-04-10 22:55:41 -07005112 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005113 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005114 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005115 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005116
chaviw50da5042018-04-09 13:49:37 -07005117 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005118 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005119 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005120
chaviwa76b2712017-09-20 12:02:26 -07005121 traverseLayers([&](Layer* layer) {
5122 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07005123 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005124 if (filtering) layer->setFiltering(false);
5125 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005126}
5127
chaviwa76b2712017-09-20 12:02:26 -07005128status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5129 TraverseLayersFunction traverseLayers,
5130 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005131 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005132 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005133 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005134 ATRACE_CALL();
5135
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005136 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005137
5138 traverseLayers([&](Layer* layer) {
5139 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5140 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005141
Robert Carr03480e22018-01-04 16:02:06 -08005142 // We allow the system server to take screenshots of secure layers for
5143 // use in situations like the Screen-rotation animation and place
5144 // the impetus on WindowManager to not persist them.
5145 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005146 ALOGW("FB is protected: PERMISSION_DENIED");
5147 return PERMISSION_DENIED;
5148 }
5149
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005150 // this binds the given EGLImage as a framebuffer for the
5151 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005152 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005153 if (bufferBond.getStatus() != NO_ERROR) {
5154 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005155 return INVALID_OPERATION;
5156 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005157
Dan Stozaabcda352017-06-01 14:37:39 -07005158 // this will in fact render into our dequeued buffer
5159 // via an FBO, which means we didn't have to create
5160 // an EGLSurface and therefore we're not
5161 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005162 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005163
Dan Stozaabcda352017-06-01 14:37:39 -07005164 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005165 getRenderEngine().finish();
5166 *outSyncFd = -1;
5167
chaviwa76b2712017-09-20 12:02:26 -07005168 const auto reqWidth = renderArea.getReqWidth();
5169 const auto reqHeight = renderArea.getReqHeight();
5170
Dan Stozaabcda352017-06-01 14:37:39 -07005171 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5172 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005173 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005174 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005175 } else {
5176 base::unique_fd syncFd = getRenderEngine().flush();
5177 if (syncFd < 0) {
5178 getRenderEngine().finish();
5179 }
5180 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005181 }
5182
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005183 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005184}
5185
Mathias Agopiand5556842013-09-19 17:08:37 -07005186void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005187 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005188 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005189 for (size_t y = 0; y < h; y++) {
5190 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5191 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005192 if (p[x] != 0xFF000000) return;
5193 }
5194 }
chaviwa76b2712017-09-20 12:02:26 -07005195 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005196
Robert Carr2047fae2016-11-28 14:09:09 -08005197 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005198 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005199 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005200 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5201 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5202 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5203 static_cast<float>(state.color.a));
5204 i++;
5205 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005206 }
5207}
5208
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005209// ---------------------------------------------------------------------------
5210
Dan Stoza412903f2017-04-27 13:42:17 -07005211void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5212 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005213}
5214
Dan Stoza412903f2017-04-27 13:42:17 -07005215void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5216 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005217}
5218
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005219void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5220 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005221 const LayerVector::Visitor& visitor) {
5222 // We loop through the first level of layers without traversing,
5223 // as we need to interpret min/max layer Z in the top level Z space.
5224 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005225 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005226 continue;
5227 }
5228 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005229 // relative layers are traversed in Layer::traverseInZOrder
5230 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005231 continue;
5232 }
5233 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005234 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005235 return;
5236 }
chaviwa76b2712017-09-20 12:02:26 -07005237 if (!layer->isVisible()) {
5238 return;
5239 }
5240 visitor(layer);
5241 });
5242 }
5243}
5244
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005245}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005246
Chia-I Wu30505fb2018-03-26 16:20:31 -07005247
Mathias Agopian3f844832013-08-07 21:24:32 -07005248#if defined(__gl_h_)
5249#error "don't include gl/gl.h in this file"
5250#endif
5251
5252#if defined(__gl2_h_)
5253#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005254#endif