blob: 2d6d4704fa3b028aea4637100ac73c5ea0b6fe3a [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();
David Sodman0756cdd2018-04-13 11:26:33 -0700780 ALOGV("Displays initialized");
Andy McFadden13a082e2012-08-24 10:16:42 -0700781
David Sodmanbc815282017-11-05 18:57:52 -0800782 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700783
Wei Wangf9b05ee2017-07-19 20:59:39 -0700784 // Inform native graphics APIs whether the present timestamp is supported:
785 if (getHwComposer().hasCapability(
786 HWC2::Capability::PresentFenceIsNotReliable)) {
787 mStartPropertySetThread = new StartPropertySetThread(false);
788 } else {
789 mStartPropertySetThread = new StartPropertySetThread(true);
790 }
791
792 if (mStartPropertySetThread->Start() != NO_ERROR) {
793 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800794 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800795
Chia-I Wud49d6692018-06-27 07:17:41 +0800796 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
797 // is used to saturate legacy sRGB content. However, to make sure the same color under
798 // Display P3 will be saturated to the same color, we intentionally break the API spec
799 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
800 // such saturation matrix on Display P3 is understood fully, the API should always return
801 // identify matrix.
802 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
803 Dataspace::SRGB_LINEAR);
804
805 // we will apply this on Display P3.
806 if (mEnhancedSaturationMatrix != mat4()) {
807 ColorSpace srgb(ColorSpace::sRGB());
808 ColorSpace displayP3(ColorSpace::DisplayP3());
809 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
810 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
811 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
812 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800813
Dan Stoza9e56aa02015-11-02 13:00:03 -0800814 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700815}
816
Romain Guy11d63f42017-07-20 12:47:14 -0700817void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700818 Mutex::Autolock _l(mStateLock);
819
Romain Guy11d63f42017-07-20 12:47:14 -0700820 char value[PROPERTY_VALUE_MAX];
821
822 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800823 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700824 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800825 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100826
827 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700828 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700829}
830
Mathias Agopiana67e4182012-06-19 17:26:12 -0700831void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800832 // Start boot animation service by setting a property mailbox
833 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700834 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800835 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700836 if (mStartPropertySetThread->join() != NO_ERROR) {
837 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800838 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700839}
840
Mathias Agopian875d8e12013-06-07 15:35:48 -0700841size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800842 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700843}
844
Mathias Agopian875d8e12013-06-07 15:35:48 -0700845size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800846 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700847}
848
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800849// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800850
Jamie Gennis582270d2011-08-17 18:19:00 -0700851bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800852 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800853 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800854 return authenticateSurfaceTextureLocked(bufferProducer);
855}
856
857bool SurfaceFlinger::authenticateSurfaceTextureLocked(
858 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800859 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800860 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800861}
862
Brian Anderson6b376712017-04-04 10:51:39 -0700863status_t SurfaceFlinger::getSupportedFrameTimestamps(
864 std::vector<FrameEvent>* outSupported) const {
865 *outSupported = {
866 FrameEvent::REQUESTED_PRESENT,
867 FrameEvent::ACQUIRE,
868 FrameEvent::LATCH,
869 FrameEvent::FIRST_REFRESH_START,
870 FrameEvent::LAST_REFRESH_START,
871 FrameEvent::GPU_COMPOSITION_DONE,
872 FrameEvent::DEQUEUE_READY,
873 FrameEvent::RELEASE,
874 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700875 ConditionalLock _l(mStateLock,
876 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700877 if (!getHwComposer().hasCapability(
878 HWC2::Capability::PresentFenceIsNotReliable)) {
879 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
880 }
881 return NO_ERROR;
882}
883
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700884status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
885 Vector<DisplayInfo>* configs) {
886 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700887 return BAD_VALUE;
888 }
889
Jesse Hall692c7232012-11-08 15:41:56 -0800890 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700891 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
892 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700893 type = i;
894 break;
895 }
896 }
897
898 if (type < 0) {
899 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700900 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700901
Mathias Agopian8b736f12012-08-13 17:54:26 -0700902 // TODO: Not sure if display density should handled by SF any longer
903 class Density {
904 static int getDensityFromProperty(char const* propName) {
905 char property[PROPERTY_VALUE_MAX];
906 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800907 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700908 density = atoi(property);
909 }
910 return density;
911 }
912 public:
913 static int getEmuDensity() {
914 return getDensityFromProperty("qemu.sf.lcd_density"); }
915 static int getBuildDensity() {
916 return getDensityFromProperty("ro.sf.lcd_density"); }
917 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700918
Dan Stoza7f7da322014-05-02 15:26:25 -0700919 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700920
Steven Thomas6d8110b2017-08-31 18:24:21 -0700921 ConditionalLock _l(mStateLock,
922 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800923 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700924 DisplayInfo info = DisplayInfo();
925
Dan Stoza9e56aa02015-11-02 13:00:03 -0800926 float xdpi = hwConfig->getDpiX();
927 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700928
929 if (type == DisplayDevice::DISPLAY_PRIMARY) {
930 // The density of the device is provided by a build property
931 float density = Density::getBuildDensity() / 160.0f;
932 if (density == 0) {
933 // the build doesn't provide a density -- this is wrong!
934 // use xdpi instead
935 ALOGE("ro.sf.lcd_density must be defined as a build property");
936 density = xdpi / 160.0f;
937 }
938 if (Density::getEmuDensity()) {
939 // if "qemu.sf.lcd_density" is specified, it overrides everything
940 xdpi = ydpi = density = Density::getEmuDensity();
941 density /= 160.0f;
942 }
943 info.density = density;
944
945 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700946 const auto display = getDefaultDisplayDeviceLocked();
947 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700948 } else {
949 // TODO: where should this value come from?
950 static const int TV_DENSITY = 213;
951 info.density = TV_DENSITY / 160.0f;
952 info.orientation = 0;
953 }
954
Dan Stoza9e56aa02015-11-02 13:00:03 -0800955 info.w = hwConfig->getWidth();
956 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700957 info.xdpi = xdpi;
958 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800959 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900960 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800961
Andy McFadden91b2ca82014-06-13 14:04:23 -0700962 // This is how far in advance a buffer must be queued for
963 // presentation at a given time. If you want a buffer to appear
964 // on the screen at time N, you must submit the buffer before
965 // (N - presentationDeadline).
966 //
967 // Normally it's one full refresh period (to give SF a chance to
968 // latch the buffer), but this can be reduced by configuring a
969 // DispSync offset. Any additional delays introduced by the hardware
970 // composer or panel must be accounted for here.
971 //
972 // We add an additional 1ms to allow for processing time and
973 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800974 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800975 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700976
977 // All non-virtual displays are currently considered secure.
978 info.secure = true;
979
Iris Chang7501ed62018-04-30 14:45:42 +0800980 if (type == DisplayDevice::DISPLAY_PRIMARY &&
981 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
982 std::swap(info.w, info.h);
983 }
984
Michael Wright28f24d02016-07-12 13:30:53 -0700985 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700986 }
987
Dan Stoza7f7da322014-05-02 15:26:25 -0700988 return NO_ERROR;
989}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700990
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700991status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
992 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700993 return BAD_VALUE;
994 }
995
996 // FIXME for now we always return stats for the primary display
997 memset(stats, 0, sizeof(*stats));
998 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
999 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
1000 return NO_ERROR;
1001}
1002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001003int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
1004 const auto display = getDisplayDevice(displayToken);
1005 if (!display) {
1006 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +08001007 return BAD_VALUE;
1008 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001009
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001010 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -07001011}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001013void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
1014 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001015 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001016 return;
1017 }
1018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001019 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001020 ALOGW("Trying to set config for virtual display");
1021 return;
1022 }
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024 display->setActiveConfig(mode);
1025 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001026}
1027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001028status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001029 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001030 Vector<DisplayInfo> configs;
1031 getDisplayConfigs(displayToken, &configs);
1032 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
1033 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
1034 configs.size());
1035 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001036 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001037 const auto display = getDisplayDevice(displayToken);
1038 if (!display) {
1039 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
1040 displayToken.get());
1041 } else if (display->isVirtual()) {
1042 ALOGW("Attempt to set active config %d for virtual display", mode);
1043 } else {
1044 setActiveConfigInternal(display, mode);
1045 }
1046 }));
1047
Mathias Agopian888c8222012-08-04 21:10:38 -07001048 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001049}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1051 Vector<ColorMode>* outColorModes) {
1052 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001053 return BAD_VALUE;
1054 }
1055
Michael Wright28f24d02016-07-12 13:30:53 -07001056 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001057 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1058 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001059 type = i;
1060 break;
1061 }
1062 }
1063
1064 if (type < 0) {
1065 return type;
1066 }
1067
Peiyong Lina52f0292018-03-14 17:26:31 -07001068 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001069 {
1070 ConditionalLock _l(mStateLock,
1071 std::this_thread::get_id() != mMainThreadId);
1072 modes = getHwComposer().getColorModes(type);
1073 }
Michael Wright28f24d02016-07-12 13:30:53 -07001074 outColorModes->clear();
1075 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1076
1077 return NO_ERROR;
1078}
1079
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1081 if (const auto display = getDisplayDevice(displayToken)) {
1082 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001083 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001084 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001085}
1086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001087void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1088 Dataspace dataSpace, RenderIntent renderIntent) {
1089 ColorMode currentMode = display->getActiveColorMode();
1090 Dataspace currentDataSpace = display->getCompositionDataSpace();
1091 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001092
Peiyong Lin38e9a562018-04-10 16:24:20 -07001093 if (mode == currentMode && dataSpace == currentDataSpace &&
1094 renderIntent == currentRenderIntent) {
1095 return;
1096 }
1097
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001098 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001099 ALOGW("Trying to set config for virtual display");
1100 return;
1101 }
1102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103 display->setActiveColorMode(mode);
1104 display->setCompositionDataSpace(dataSpace);
1105 display->setActiveRenderIntent(renderIntent);
1106 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001107
1108 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001109 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1110 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001111}
1112
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001113status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001114 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115 Vector<ColorMode> modes;
1116 getDisplayColorModes(displayToken, &modes);
1117 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1118 if (mode < ColorMode::NATIVE || !exists) {
1119 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1120 decodeColorMode(mode).c_str(), mode, displayToken.get());
1121 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001122 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001123 const auto display = getDisplayDevice(displayToken);
1124 if (!display) {
1125 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1126 decodeColorMode(mode).c_str(), mode, displayToken.get());
1127 } else if (display->isVirtual()) {
1128 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1129 decodeColorMode(mode).c_str(), mode);
1130 } else {
1131 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1132 RenderIntent::COLORIMETRIC);
1133 }
1134 }));
1135
Michael Wright28f24d02016-07-12 13:30:53 -07001136 return NO_ERROR;
1137}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001138
Svetoslavd85084b2014-03-20 10:28:31 -07001139status_t SurfaceFlinger::clearAnimationFrameStats() {
1140 Mutex::Autolock _l(mStateLock);
1141 mAnimFrameTracker.clearStats();
1142 return NO_ERROR;
1143}
1144
1145status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1146 Mutex::Autolock _l(mStateLock);
1147 mAnimFrameTracker.getStats(outStats);
1148 return NO_ERROR;
1149}
1150
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001151status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1152 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001153 Mutex::Autolock _l(mStateLock);
1154
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001155 const auto display = getDisplayDeviceLocked(displayToken);
1156 if (!display) {
1157 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001158 return BAD_VALUE;
1159 }
1160
Peiyong Linfb069302018-04-25 14:34:31 -07001161 // At this point the DisplayDeivce should already be set up,
1162 // meaning the luminance information is already queried from
1163 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001164 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001165 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1166 capabilities.getDesiredMaxLuminance(),
1167 capabilities.getDesiredMaxAverageLuminance(),
1168 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001169
1170 return NO_ERROR;
1171}
1172
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001173status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001174 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001175 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001176
Chia-I Wu90f669f2017-10-05 14:24:41 -07001177 if (mInjectVSyncs == enable) {
1178 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001179 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001180
1181 if (enable) {
1182 ALOGV("VSync Injections enabled");
1183 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001184 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001185 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001186 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001187 impl::EventThread::InterceptVSyncsCallback(),
1188 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001189 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001190 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001191 } else {
1192 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001193 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001194 }
1195
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001196 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001197 }));
1198
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001199 return NO_ERROR;
1200}
1201
1202status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001203 Mutex::Autolock _l(mStateLock);
1204
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001205 if (!mInjectVSyncs) {
1206 ALOGE("VSync Injections not enabled");
1207 return BAD_VALUE;
1208 }
1209 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1210 ALOGV("Injecting VSync inside SurfaceFlinger");
1211 mVSyncInjector->onInjectSyncEvent(when);
1212 }
1213 return NO_ERROR;
1214}
1215
Lloyd Pique755e3192018-01-31 16:46:15 -08001216status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1217 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001218 IPCThreadState* ipc = IPCThreadState::self();
1219 const int pid = ipc->getCallingPid();
1220 const int uid = ipc->getCallingUid();
1221 if ((uid != AID_SHELL) &&
1222 !PermissionCache::checkPermission(sDump, pid, uid)) {
1223 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1224 return PERMISSION_DENIED;
1225 }
1226
1227 // Try to acquire a lock for 1s, fail gracefully
1228 const status_t err = mStateLock.timedLock(s2ns(1));
1229 const bool locked = (err == NO_ERROR);
1230 if (!locked) {
1231 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1232 return TIMED_OUT;
1233 }
1234
1235 outLayers->clear();
1236 mCurrentState.traverseInZOrder([&](Layer* layer) {
1237 outLayers->push_back(layer->getLayerDebugInfo());
1238 });
1239
1240 mStateLock.unlock();
1241 return NO_ERROR;
1242}
1243
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001244// ----------------------------------------------------------------------------
1245
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001246sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1247 ISurfaceComposer::VsyncSource vsyncSource) {
1248 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1249 return mSFEventThread->createEventConnection();
1250 } else {
1251 return mEventThread->createEventConnection();
1252 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001253}
1254
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001255// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001256
1257void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001258 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001259}
1260
1261void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001262 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001263}
1264
1265void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001266 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001267}
1268
1269void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001270 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001271 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001272}
1273
1274status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001275 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001276 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001277}
1278
1279status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001280 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001281 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001282 if (res == NO_ERROR) {
1283 msg->wait();
1284 }
1285 return res;
1286}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001287
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001288void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001289 do {
1290 waitForEvent();
1291 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001292}
1293
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294void SurfaceFlinger::enableHardwareVsync() {
1295 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001296 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001298 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001299 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001300 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001301}
1302
Jesse Hall948fe0c2013-10-14 12:56:09 -07001303void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001304 Mutex::Autolock _l(mHWVsyncLock);
1305
Jesse Hall948fe0c2013-10-14 12:56:09 -07001306 if (makeAvailable) {
1307 mHWVsyncAvailable = true;
1308 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001309 // Hardware vsync is not currently available, so abort the resync
1310 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001311 return;
1312 }
1313
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001314 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1315 if (!getHwComposer().isConnected(displayId)) {
1316 return;
1317 }
1318
1319 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001320 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001321
1322 mPrimaryDispSync.reset();
1323 mPrimaryDispSync.setPeriod(period);
1324
1325 if (!mPrimaryHWVsyncEnabled) {
1326 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001327 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001328 mPrimaryHWVsyncEnabled = true;
1329 }
1330}
1331
Jesse Hall948fe0c2013-10-14 12:56:09 -07001332void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001333 Mutex::Autolock _l(mHWVsyncLock);
1334 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001335 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001336 mPrimaryDispSync.endResync();
1337 mPrimaryHWVsyncEnabled = false;
1338 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001339 if (makeUnavailable) {
1340 mHWVsyncAvailable = false;
1341 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001342}
1343
Tim Murray4a4e4a22016-04-19 16:29:23 +00001344void SurfaceFlinger::resyncWithRateLimit() {
1345 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001346
1347 // No explicit locking is needed here since EventThread holds a lock while calling this method
1348 static nsecs_t sLastResyncAttempted = 0;
1349 const nsecs_t now = systemTime();
1350 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001351 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001352 }
Dan Stoza57164302017-05-08 14:03:54 -07001353 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001354}
1355
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001356void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1357 int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001358 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001360 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001361 return;
1362 }
1363
1364 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001365 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001366 return;
1367 }
1368
Jamie Gennisd1700752013-10-14 12:22:52 -07001369 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001370
Jamie Gennisd1700752013-10-14 12:22:52 -07001371 { // Scope for the lock
1372 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001374 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001375 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001376 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001377
1378 if (needsHwVsync) {
1379 enableHardwareVsync();
1380 } else {
1381 disableHardwareVsync(false);
1382 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001383}
1384
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001385void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001386 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1387 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001388}
1389
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001390void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001391 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001392 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001393 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001394
Lloyd Piqueba04e622017-12-14 17:11:26 -08001395 // Ignore events that do not have the right sequenceId.
1396 if (sequenceId != getBE().mComposerSequenceId) {
1397 return;
1398 }
1399
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 // Only lock if we're not on the main thread. This function is normally
1401 // called on a hwbinder thread, but for the primary display it's called on
1402 // the main thread with the state lock already held, so don't attempt to
1403 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001404 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001405
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001406 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001407
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001408 if (std::this_thread::get_id() == mMainThreadId) {
1409 // Process all pending hot plug events immediately if we are on the main thread.
1410 processDisplayHotplugEventsLocked();
1411 }
1412
Lloyd Piqueba04e622017-12-14 17:11:26 -08001413 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001414}
1415
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001416void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001417 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001418 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001420 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001421 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001422}
1423
Dan Stoza9e56aa02015-11-02 13:00:03 -08001424void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001425 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001426 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001427 getHwComposer().setVsyncEnabled(disp,
1428 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001429}
1430
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001431// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001432void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001433 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001434 // Clear the drawing state so that the logic inside of
1435 // handleTransactionLocked will fire. It will determine the delta between
1436 // mCurrentState and mDrawingState and re-apply all changes when we make the
1437 // transition.
1438 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001439 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001440 mDisplays.clear();
1441}
1442
Steven Thomas050b2c82017-03-06 11:45:16 -08001443void SurfaceFlinger::updateVrFlinger() {
1444 if (!mVrFlinger)
1445 return;
1446 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001447 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001448 return;
1449 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001450
David Sodman105b7dc2017-11-04 20:28:14 -07001451 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001452 ALOGE("Vr flinger is only supported for remote hardware composer"
1453 " service connections. Ignoring request to transition to vr"
1454 " flinger.");
1455 mVrFlingerRequestsDisplay = false;
1456 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001457 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001458
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001459 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001460
Steven Thomas0123ac62018-07-12 11:32:34 -07001461 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001462 LOG_ALWAYS_FATAL_IF(!display);
1463 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001464 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1465 // called below. Clear the reference now so we don't accidentally use it
1466 // later.
1467 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001468
Steven Thomasb02664d2017-07-26 18:48:28 -07001469 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001470 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001471 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001472
Steven Thomasb02664d2017-07-26 18:48:28 -07001473 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001474 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001475 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1476 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001477 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001478
David Sodman105b7dc2017-11-04 20:28:14 -07001479 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1480 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001481
1482 if (vrFlingerRequestsDisplay) {
1483 mVrFlinger->GrantDisplayOwnership();
1484 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001485 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001486 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001487
1488 mVisibleRegionsDirty = true;
1489 invalidateHwcGeometry();
1490
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001491 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001492 display = getDefaultDisplayDeviceLocked();
1493 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001494 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001495
Steven Thomasb02664d2017-07-26 18:48:28 -07001496 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001497 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001498 const nsecs_t period = activeConfig->getVsyncPeriod();
1499 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001500
Steven Thomasb02664d2017-07-26 18:48:28 -07001501 // Use phase of 0 since phase is not known.
1502 // Use latency of 0, which will snap to the ideal latency.
1503 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001504
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001505 android_atomic_or(1, &mRepaintEverything);
1506 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001507}
1508
Mathias Agopian4fec8732012-06-29 14:12:52 -07001509void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001510 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001511 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001512 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001513 bool frameMissed = !mHadClientComposition &&
1514 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001515 (mPreviousPresentFence->getSignalTime() ==
1516 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001517 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001518 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001519 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001520 mTimeStats.incrementMissedFrames();
1521 if (mPropagateBackpressure) {
1522 signalLayerUpdate();
1523 break;
1524 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001525 }
Dan Stoza50182882016-07-08 12:02:20 -07001526
Steven Thomas050b2c82017-03-06 11:45:16 -08001527 // Now that we're going to make it to the handleMessageTransaction()
1528 // call below it's safe to call updateVrFlinger(), which will
1529 // potentially trigger a display handoff.
1530 updateVrFlinger();
1531
Dan Stoza6b9454d2014-11-07 16:00:59 -08001532 bool refreshNeeded = handleMessageTransaction();
1533 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001534 refreshNeeded |= mRepaintEverything;
David Sodman0756cdd2018-04-13 11:26:33 -07001535
1536 preComposition();
1537 rebuildLayerStacks();
1538 calculateWorkingSet();
1539
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001540 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
David Sodman0756cdd2018-04-13 11:26:33 -07001541
Dan Stoza58784442014-12-02 16:58:17 -08001542 // Signal a refresh if a transaction modified the window state,
1543 // a new buffer was latched, or if HWC has requested a full
1544 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001545 signalRefresh();
1546 }
1547 break;
1548 }
1549 case MessageQueue::REFRESH: {
1550 handleMessageRefresh();
1551 break;
1552 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001553 }
1554}
1555
Dan Stoza6b9454d2014-11-07 16:00:59 -08001556bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001557 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001558 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001559 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001560 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001561 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001562 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001563}
1564
Dan Stoza6b9454d2014-11-07 16:00:59 -08001565bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001566 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001567 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001568}
1569
David Sodman0756cdd2018-04-13 11:26:33 -07001570void SurfaceFlinger::calculateWorkingSet() {
1571 ATRACE_CALL();
1572 ALOGV(__FUNCTION__);
1573
1574 // build the h/w work list
1575 if (CC_UNLIKELY(mGeometryInvalid)) {
1576 mGeometryInvalid = false;
1577 for (const auto& [token, display] : mDisplays) {
1578 const auto displayId = display->getId();
1579 if (displayId >= 0) {
1580 const Vector<sp<Layer>>& currentLayers(
1581 display->getVisibleLayersSortedByZ());
1582 for (size_t i = 0; i < currentLayers.size(); i++) {
1583 const auto& layer = currentLayers[i];
1584
1585 if (!layer->hasHwcLayer(displayId)) {
1586 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1587 layer->forceClientComposition(displayId);
1588 continue;
1589 }
1590 }
1591
1592 layer->setGeometry(display, i);
1593 if (mDebugDisableHWC || mDebugRegion) {
1594 layer->forceClientComposition(displayId);
1595 }
1596 }
1597 }
1598 }
1599 }
1600
1601 // Set the per-frame data
1602 for (const auto& [token, display] : mDisplays) {
1603 const auto displayId = display->getId();
1604 if (displayId < 0) {
1605 continue;
1606 }
1607
1608 if (mDrawingState.colorMatrixChanged) {
1609 display->setColorTransform(mDrawingState.colorMatrix);
1610 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1611 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1612 "display %d: %d", displayId, result);
1613 }
1614 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1615 if (layer->isHdrY410()) {
1616 layer->forceClientComposition(displayId);
1617 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1618 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1619 !display->hasHDR10Support()) {
1620 layer->forceClientComposition(displayId);
1621 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1622 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1623 !display->hasHLGSupport()) {
1624 layer->forceClientComposition(displayId);
1625 }
1626
1627 if (layer->getForceClientComposition(displayId)) {
1628 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1629 layer->setCompositionType(displayId, HWC2::Composition::Client);
1630 continue;
1631 }
1632
1633 layer->setPerFrameData(display);
1634 }
1635
1636 if (hasWideColorDisplay) {
1637 ColorMode colorMode;
1638 Dataspace dataSpace;
1639 RenderIntent renderIntent;
1640 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1641 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1642 }
1643 }
1644
1645 mDrawingState.colorMatrixChanged = false;
1646 getBE().mCompositionInfo.clear();
1647
1648 for (const auto& [token, display] : mDisplays) {
1649 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1650 auto displayId = display->getId();
1651 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1652 if (!layer->setHwcLayer(displayId)) {
1653 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1654 }
1655 getBE().mCompositionInfo.push_back(layer->getBE().compositionInfo);
1656 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1657 }
1658 }
1659}
1660
Mathias Agopian4fec8732012-06-29 14:12:52 -07001661void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001662 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001663
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001664 mRefreshPending = false;
1665
David Sodman0756cdd2018-04-13 11:26:33 -07001666 beginFrame();
1667 for (auto compositionInfo : getBE().mCompositionInfo) {
1668 setUpHWComposer(compositionInfo);
1669 }
1670 prepareFrame();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001671 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001672 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001673 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001674 doComposition();
David Sodman0756cdd2018-04-13 11:26:33 -07001675 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001676
Dan Stozabfbffeb2016-07-21 14:49:33 -07001677 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001678 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001679 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001680 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001681 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001682 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001683
Dan Stoza9e56aa02015-11-02 13:00:03 -08001684 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001685}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001686
Mathias Agopiancd60f992012-08-16 16:28:27 -07001687void SurfaceFlinger::doDebugFlashRegions()
1688{
1689 // is debugging enabled
1690 if (CC_LIKELY(!mDebugRegion))
1691 return;
1692
1693 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001694 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001695 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001696 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001697 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001698 if (!dirtyRegion.isEmpty()) {
1699 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001700 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001701
1702 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001703 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001704 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001705 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1706
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001707 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001708 }
1709 }
1710 }
1711
1712 postFramebuffer();
1713
1714 if (mDebugRegion > 1) {
1715 usleep(mDebugRegion * 1000);
1716 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001717
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001718 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001719 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001720 continue;
1721 }
1722
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001723 status_t result = display->prepareFrame(*getBE().mHwc);
1724 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001725 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001726 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001727}
1728
Adrian Roos1e1a1282017-11-01 19:05:31 +01001729void SurfaceFlinger::doTracing(const char* where) {
1730 ATRACE_CALL();
1731 ATRACE_NAME(where);
1732 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001733 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001734 }
1735}
1736
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001737void SurfaceFlinger::logLayerStats() {
1738 ATRACE_CALL();
1739 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001740 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001741 if (display->isPrimary()) {
1742 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001743 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001744 }
1745 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001746
1747 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001748 }
1749}
1750
David Sodman0756cdd2018-04-13 11:26:33 -07001751void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001752{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001753 ATRACE_CALL();
1754 ALOGV("preComposition");
1755
Mathias Agopiancd60f992012-08-16 16:28:27 -07001756 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001757 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman0756cdd2018-04-13 11:26:33 -07001758 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001759 needExtraInvalidate = true;
1760 }
Robert Carr2047fae2016-11-28 14:09:09 -08001761 });
1762
Mathias Agopiancd60f992012-08-16 16:28:27 -07001763 if (needExtraInvalidate) {
1764 signalLayerUpdate();
1765 }
1766}
1767
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001768void SurfaceFlinger::updateCompositorTiming(
1769 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1770 std::shared_ptr<FenceTime>& presentFenceTime) {
1771 // Update queue of past composite+present times and determine the
1772 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001773 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001774 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001775 while (!getBE().mCompositePresentTimes.empty()) {
1776 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001777 // Cached values should have been updated before calling this method,
1778 // which helps avoid duplicate syscalls.
1779 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1780 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1781 break;
1782 }
1783 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001784 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001785 }
1786
1787 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001788 while (getBE().mCompositePresentTimes.size() > 16) {
1789 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001790 }
1791
Brian Andersond0010582017-03-07 13:20:31 -08001792 setCompositorTimingSnapped(
1793 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1794}
1795
1796void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1797 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001798 // Integer division and modulo round toward 0 not -inf, so we need to
1799 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001800 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001801 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1802 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1803
Brian Andersond0010582017-03-07 13:20:31 -08001804 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1805 if (idealLatency <= 0) {
1806 idealLatency = vsyncInterval;
1807 }
1808
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001809 // Snap the latency to a value that removes scheduling jitter from the
1810 // composition and present times, which often have >1ms of jitter.
1811 // Reducing jitter is important if an app attempts to extrapolate
1812 // something (such as user input) to an accurate diasplay time.
1813 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1814 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001815 nsecs_t bias = vsyncInterval / 2;
1816 int64_t extraVsyncs =
1817 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1818 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1819 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001820
David Sodman99974d22017-11-28 12:04:33 -08001821 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1822 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1823 getBE().mCompositorTiming.interval = vsyncInterval;
1824 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001825}
1826
David Sodman0756cdd2018-04-13 11:26:33 -07001827void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001828{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001829 ATRACE_CALL();
1830 ALOGV("postComposition");
1831
Brian Anderson3546a3f2016-07-14 11:51:14 -07001832 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001833 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001834 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001835 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001836 }
1837
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001838 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001839 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001840
David Sodman73beded2017-11-15 11:56:06 -08001841 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001842 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001843 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001844 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001845 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001846 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001847 } else {
1848 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1849 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001850
David Sodman73beded2017-11-15 11:56:06 -08001851 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001852 mPreviousPresentFence =
1853 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1854 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001855 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001856
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001857 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1858 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1859
David Sodman0756cdd2018-04-13 11:26:33 -07001860 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001861 // when we started doing work for this frame, but that should be okay
1862 // since updateCompositorTiming has snapping logic.
1863 updateCompositorTiming(
David Sodman0756cdd2018-04-13 11:26:33 -07001864 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001865 CompositorTiming compositorTiming;
1866 {
David Sodman99974d22017-11-28 12:04:33 -08001867 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1868 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001869 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001870
Robert Carr2047fae2016-11-28 14:09:09 -08001871 mDrawingState.traverseInZOrder([&](Layer* layer) {
1872 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001873 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001874 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001875 recordBufferingStats(layer->getName().string(),
1876 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001877 }
Robert Carr2047fae2016-11-28 14:09:09 -08001878 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001879
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001880 if (presentFenceTime->isValid()) {
1881 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001882 enableHardwareVsync();
1883 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001884 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001885 }
1886 }
1887
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001888 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001889 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001890 enableHardwareVsync();
1891 }
1892 }
1893
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001894 if (mAnimCompositionPending) {
1895 mAnimCompositionPending = false;
1896
Brian Anderson4e606e32017-03-16 15:34:57 -07001897 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001898 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001899 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001900 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001901 // The HWC doesn't support present fences, so use the refresh
1902 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001903 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001904 mAnimFrameTracker.setActualPresentTime(presentTime);
1905 }
1906 mAnimFrameTracker.advanceFrame();
1907 }
Dan Stozab90cf072015-03-05 11:05:59 -08001908
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001909 mTimeStats.incrementTotalFrames();
1910 if (mHadClientComposition) {
1911 mTimeStats.incrementClientCompositionFrames();
1912 }
1913
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001914 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001915 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001916 return;
1917 }
1918
1919 nsecs_t currentTime = systemTime();
1920 if (mHasPoweredOff) {
1921 mHasPoweredOff = false;
1922 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001923 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001924 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001925 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1926 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001927 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001928 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001929 }
David Sodman4a36e932017-11-07 14:29:47 -08001930 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001931 }
David Sodman4a36e932017-11-07 14:29:47 -08001932 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001933
1934 {
1935 std::lock_guard lock(mTexturePoolMutex);
1936 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1937 if (refillCount > 0) {
1938 const size_t offset = mTexturePool.size();
1939 mTexturePool.resize(mTexturePoolSize);
1940 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1941 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1942 }
1943 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001944}
1945
1946void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001947 ATRACE_CALL();
1948 ALOGV("rebuildLayerStacks");
1949
Mathias Agopiancd60f992012-08-16 16:28:27 -07001950 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001951 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001952 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001953 mVisibleRegionsDirty = false;
1954 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001955
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001956 for (const auto& pair : mDisplays) {
1957 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001958 Region opaqueRegion;
1959 Region dirtyRegion;
1960 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001961 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001962 const Transform& tr = display->getTransform();
1963 const Rect bounds = display->getBounds();
1964 if (display->isPoweredOn()) {
1965 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001966
Jeff Sharkey76488112017-02-27 14:15:18 -07001967 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001968 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001969 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001970 Region drawRegion(tr.transform(
1971 layer->visibleNonTransparentRegion));
1972 drawRegion.andSelf(bounds);
1973 if (!drawRegion.isEmpty()) {
1974 layersSortedByZ.add(layer);
1975 } else {
David Sodman0756cdd2018-04-13 11:26:33 -07001976 if (layer->hasHwcLayer(display->getId())) {
1977 // Clear out the HWC layer if this layer was
1978 // previously visible, but no longer is
1979 hwcLayerDestroyed = layer->destroyHwcLayer(
1980 display->getId());
1981 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001982 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001983 } else {
David Sodman0756cdd2018-04-13 11:26:33 -07001984 if (layer->hasHwcLayer(display->getId())) {
1985 // WM changes display->layerStack upon sleep/awake.
1986 // Here we make sure we delete the HWC layers even if
1987 // WM changed their layer stack.
1988 hwcLayerDestroyed = layer->destroyHwcLayer(
1989 display->getId());
1990 }
Chia-I Wu83806892017-11-16 10:50:20 -08001991 }
1992
1993 // If a layer is not going to get a release fence because
1994 // it is invisible, but it is also going to release its
1995 // old buffer, add it to the list of layers needing
1996 // fences.
1997 if (hwcLayerDestroyed) {
1998 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1999 mLayersWithQueuedFrames.cend(), layer);
2000 if (found != mLayersWithQueuedFrames.cend()) {
2001 layersNeedingFences.add(layer);
2002 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002003 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002004 });
2005 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002006 display->setVisibleLayersSortedByZ(layersSortedByZ);
2007 display->setLayersNeedingFences(layersNeedingFences);
2008 display->undefinedRegion.set(bounds);
2009 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2010 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002011 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002012 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002013}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002014
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002015// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002016// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002017// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002018// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002019// The returned HDR data space is one of
2020// - Dataspace::UNKNOWN
2021// - Dataspace::BT2020_HLG
2022// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002023Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2024 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002025 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002026 *outHdrDataSpace = Dataspace::UNKNOWN;
2027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002028 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002029 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002030 case Dataspace::V0_SCRGB:
2031 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002032 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002033 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002034 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002035 case Dataspace::BT2020_PQ:
2036 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002037 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002038 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002039 case Dataspace::BT2020_HLG:
2040 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002041 // When there's mixed PQ content and HLG content, we set the HDR
2042 // data space to be BT2020_PQ and convert HLG to PQ.
2043 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2044 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002045 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002046 break;
2047 default:
2048 break;
2049 }
Romain Guy54f154a2017-10-24 21:40:32 +01002050 }
2051
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002052 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002053}
2054
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002055// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002056void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2057 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002058 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2059 *outMode = ColorMode::NATIVE;
2060 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002061 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002062 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002063 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002064
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002065 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002066 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002067
Peiyong Lindfde5112018-06-05 10:58:41 -07002068 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002069 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002070 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002071 if (isHdr) {
2072 bestDataSpace = hdrDataSpace;
2073 }
2074
Chia-I Wu0d711262018-05-21 15:19:35 -07002075 RenderIntent intent;
2076 switch (mDisplayColorSetting) {
2077 case DisplayColorSetting::MANAGED:
2078 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002079 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002080 break;
2081 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002082 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002083 break;
2084 default: // vendor display color setting
2085 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2086 break;
2087 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002088
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002089 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002090}
2091
David Sodman0756cdd2018-04-13 11:26:33 -07002092void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2093{
2094 HWC2::Error error;
2095 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2096 "CompositionType is sideband, but sideband stream is nullptr");
2097 error = (compositionInfo.hwc.hwcLayer)
2098 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2099 if (error != HWC2::Error::None) {
2100 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2101 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2102 static_cast<int32_t>(error));
2103 }
2104}
2105
2106void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2107{
2108 HWC2::Error error;
2109
2110 if (!compositionInfo.hwc.skipGeometry) {
2111 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2112 ALOGE_IF(error != HWC2::Error::None,
2113 "[SF] Failed to set blend mode %s:"
2114 " %s (%d)",
2115 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2116 static_cast<int32_t>(error));
2117
2118 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2119 ALOGE_IF(error != HWC2::Error::None,
2120 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2121 compositionInfo.hwc.displayFrame.left,
2122 compositionInfo.hwc.displayFrame.right,
2123 compositionInfo.hwc.displayFrame.top,
2124 compositionInfo.hwc.displayFrame.bottom,
2125 to_string(error).c_str(), static_cast<int32_t>(error));
2126
2127 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2128 ALOGE_IF(error != HWC2::Error::None,
2129 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2130 compositionInfo.hwc.sourceCrop.left,
2131 compositionInfo.hwc.sourceCrop.right,
2132 compositionInfo.hwc.sourceCrop.top,
2133 compositionInfo.hwc.sourceCrop.bottom,
2134 to_string(error).c_str(), static_cast<int32_t>(error));
2135
2136 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2137 ALOGE_IF(error != HWC2::Error::None,
2138 "[SF] Failed to set plane alpha %.3f: "
2139 "%s (%d)",
2140 compositionInfo.hwc.alpha,
2141 to_string(error).c_str(), static_cast<int32_t>(error));
2142
2143
2144 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2145 ALOGE_IF(error != HWC2::Error::None,
2146 "[SF] Failed to set Z %u: %s (%d)",
2147 compositionInfo.hwc.z,
2148 to_string(error).c_str(), static_cast<int32_t>(error));
2149
2150 error = (compositionInfo.hwc.hwcLayer)
2151 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2152 ALOGE_IF(error != HWC2::Error::None,
2153 "[SF] Failed to set info (%d)",
2154 static_cast<int32_t>(error));
2155
2156 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2157 ALOGE_IF(error != HWC2::Error::None,
2158 "[SF] Failed to set transform %s: "
2159 "%s (%d)",
2160 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2161 static_cast<int32_t>(error));
2162 }
2163
2164 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2165 ALOGE_IF(error != HWC2::Error::None,
2166 "[SF] Failed to set composition type: %s (%d)",
2167 to_string(error).c_str(), static_cast<int32_t>(error));
2168
2169 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2170 ALOGE_IF(error != HWC2::Error::None,
2171 "[SF] Failed to set dataspace: %s (%d)",
2172 to_string(error).c_str(), static_cast<int32_t>(error));
2173
2174 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2175 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2176 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2177 "[SF] Failed to set hdrMetadata: %s (%d)",
2178 to_string(error).c_str(), static_cast<int32_t>(error));
2179
2180 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2181 ALOGE_IF(error != HWC2::Error::None,
2182 "[SF] Failed to set color: %s (%d)",
2183 to_string(error).c_str(), static_cast<int32_t>(error));
2184
2185 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2186 ALOGE_IF(error != HWC2::Error::None,
2187 "[SF] Failed to set visible region: %s (%d)",
2188 to_string(error).c_str(), static_cast<int32_t>(error));
2189}
2190
2191void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2192{
2193 HWC2::Error error;
2194
2195 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2196 ALOGE_IF(error != HWC2::Error::None,
2197 "[SF] Failed to set surface damage: %s (%d)",
2198 to_string(error).c_str(), static_cast<int32_t>(error));
2199
2200 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2201 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2202 ALOGE_IF(error != HWC2::Error::None,
2203 "[SF] Failed to set buffer: %s (%d)",
2204 to_string(error).c_str(), static_cast<int32_t>(error));
2205}
2206
2207void SurfaceFlinger::beginFrame()
2208{
2209 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002210
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002211 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002212 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
2213 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2214 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07002215
2216 // If nothing has changed (!dirty), don't recompose.
2217 // If something changed, but we don't currently have any visible layers,
2218 // and didn't when we last did a composition, then skip it this time.
2219 // The second rule does two things:
2220 // - When all layers are removed from a display, we'll emit one black
2221 // frame, then nothing more until we get new layers.
2222 // - When a display is created with a private layer stack, we won't
2223 // emit any black frames until a layer is added to the layer stack.
2224 bool mustRecompose = dirty && !(empty && wasEmpty);
2225
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002226 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002227 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
2228 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07002229
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002230 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002231
2232 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002233 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07002234 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002235 }
David Sodman0756cdd2018-04-13 11:26:33 -07002236}
Jesse Hall028dc8f2013-08-20 16:35:32 -07002237
David Sodman0756cdd2018-04-13 11:26:33 -07002238void SurfaceFlinger::prepareFrame()
2239{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002240 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002241 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002242 continue;
2243 }
2244
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002245 status_t result = display->prepareFrame(*getBE().mHwc);
2246 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002247 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002248 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002249}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002250
David Sodman0756cdd2018-04-13 11:26:33 -07002251void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2252 ATRACE_CALL();
2253 ALOGV("setUpHWComposer");
2254
2255 switch (compositionInfo.compositionType)
2256 {
2257 case HWC2::Composition::Invalid:
2258 case HWC2::Composition::Client:
2259 break;
2260
2261 case HWC2::Composition::Sideband:
2262 configureSidebandComposition(compositionInfo);
2263 break;
2264
2265 case HWC2::Composition::SolidColor:
2266 configureHwcCommonData(compositionInfo);
2267 break;
2268
2269 case HWC2::Composition::Device:
2270 case HWC2::Composition::Cursor:
2271 configureHwcCommonData(compositionInfo);
2272 configureDeviceComposition(compositionInfo);
2273 break;
2274 }
2275}
2276
Mathias Agopiancd60f992012-08-16 16:28:27 -07002277void SurfaceFlinger::doComposition() {
2278 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002279 ALOGV("doComposition");
2280
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002281 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002282 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002283 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002284 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002285 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002286
2287 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002288 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002289
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002290 display->dirtyRegion.clear();
2291 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002292 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002293 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002294 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002295}
2296
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002297void SurfaceFlinger::postFramebuffer()
2298{
Mathias Agopian841cde52012-03-01 15:44:37 -08002299 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002300 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002301
Mathias Agopiana44b0412011-10-16 18:46:35 -07002302 const nsecs_t now = systemTime();
2303 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002304
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002305 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002306 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002307 continue;
2308 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002309 const auto displayId = display->getId();
2310 if (displayId >= 0) {
2311 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002312 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002313 display->onSwapBuffersCompleted();
2314 display->makeCurrent();
2315 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002316 // The layer buffer from the previous frame (if any) is released
2317 // by HWC only when the release fence from this frame (if any) is
2318 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002319 auto hwcLayer = layer->getHwcLayer(displayId);
2320 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002321
2322 // If the layer was client composited in the previous frame, we
2323 // need to merge with the previous client target acquire fence.
2324 // Since we do not track that, always merge with the current
2325 // client target acquire fence when it is available, even though
2326 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002327 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002328 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002329 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002330 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002331
David Sodmanb8af7922017-12-21 15:17:55 -08002332 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002333 }
Chia-I Wu83806892017-11-16 10:50:20 -08002334
2335 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002336 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002337 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002338 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002339 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002340 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002341 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002342 }
2343 }
2344
Dominik Laskowski7e045462018-05-30 13:02:02 -07002345 if (displayId >= 0) {
2346 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002347 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002348 }
2349
Mathias Agopiana44b0412011-10-16 18:46:35 -07002350 mLastSwapBufferTime = systemTime() - now;
2351 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002352
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002353 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002354 const auto display = getDefaultDisplayDeviceLocked();
2355 if (display && getHwComposer().isConnected(display->getId())) {
2356 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002357 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2358 logFrameStats();
2359 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002360 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002361}
2362
Mathias Agopian87baae12012-07-31 12:38:26 -07002363void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002364{
Mathias Agopian841cde52012-03-01 15:44:37 -08002365 ATRACE_CALL();
2366
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002367 // here we keep a copy of the drawing state (that is the state that's
2368 // going to be overwritten by handleTransactionLocked()) outside of
2369 // mStateLock so that the side-effects of the State assignment
2370 // don't happen with mStateLock held (which can cause deadlocks).
2371 State drawingState(mDrawingState);
2372
Mathias Agopianca4d3602011-05-19 15:38:14 -07002373 Mutex::Autolock _l(mStateLock);
2374 const nsecs_t now = systemTime();
2375 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002376
Mathias Agopianca4d3602011-05-19 15:38:14 -07002377 // Here we're guaranteed that some transaction flags are set
2378 // so we can call handleTransactionLocked() unconditionally.
2379 // We call getTransactionFlags(), which will also clear the flags,
2380 // with mStateLock held to guarantee that mCurrentState won't change
2381 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002382
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002383 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002384 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002385 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002386
Mathias Agopianca4d3602011-05-19 15:38:14 -07002387 mLastTransactionTime = systemTime() - now;
2388 mDebugInTransaction = 0;
2389 invalidateHwcGeometry();
2390 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002391}
2392
Dominik Laskowski7e045462018-05-30 13:02:02 -07002393DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002394 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002395 // Figure out whether the event is for the primary display or an
2396 // external display by matching the Hwc display id against one for a
2397 // connected display. If we did not find a match, we then check what
2398 // displays are not already connected to determine the type. If we don't
2399 // have a connected primary display, we assume the new display is meant to
2400 // be the primary display, and then if we don't have an external display,
2401 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002402 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2403 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002404 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002405 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002406 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002407 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002408 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002409 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002410 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002411 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002412 return DisplayDevice::DISPLAY_EXTERNAL;
2413 }
2414
2415 return DisplayDevice::DISPLAY_ID_INVALID;
2416}
2417
Lloyd Piqueba04e622017-12-14 17:11:26 -08002418void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2419 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002420 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002421 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002422 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002423 continue;
2424 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002425
2426 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2427 ALOGE("External displays are not supported by the vr hardware composer.");
2428 continue;
2429 }
2430
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002431 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002432 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002433 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002434 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002435 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002436
2437 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002438 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002439 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002440 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002441 DisplayDeviceState info;
2442 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002443 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2444 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002445 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002446 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002447 mInterceptor->saveDisplayCreation(info);
2448 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002449 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002450 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002451
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002452 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002453 if (idx >= 0) {
2454 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002455 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002456 mCurrentState.displays.removeItemsAt(idx);
2457 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002458 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002459 }
2460
2461 processDisplayChangesLocked();
2462 }
2463
2464 mPendingHotplugEvents.clear();
2465}
2466
Lloyd Pique99d3da52018-01-22 17:48:03 -08002467sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002468 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002469 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002470 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002471 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002472
Lloyd Pique99d3da52018-01-22 17:48:03 -08002473 if (hasWideColorDisplay) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002474 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002475 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002476 if (isWideColorMode(colorMode)) {
2477 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002478 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002479
Dominik Laskowski7e045462018-05-30 13:02:02 -07002480 std::vector<RenderIntent> renderIntents =
2481 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002482 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002483 }
2484 }
2485
Peiyong Lin62665892018-04-16 11:07:44 -07002486 HdrCapabilities hdrCapabilities;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002487 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002488
2489 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2490 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2491
2492 /*
2493 * Create our display's surface
2494 */
2495 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2496 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002497 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002498 renderSurface->setNativeWindow(nativeWindow.get());
2499 const int displayWidth = renderSurface->queryWidth();
2500 const int displayHeight = renderSurface->queryHeight();
2501
2502 // Make sure that composition can never be stalled by a virtual display
2503 // consumer that isn't processing buffers fast enough. We have to do this
2504 // in two places:
2505 // * Here, in case the display is composed entirely by HWC.
2506 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2507 // window's swap interval in eglMakeCurrent, so they'll override the
2508 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002509 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002510 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2511 }
2512
2513 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002514 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002515
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002516 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002517 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2518 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2519 displayHeight, hasWideColorGamut, hdrCapabilities,
2520 getHwComposer().getSupportedPerFrameMetadata(displayId),
2521 hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002522
2523 if (maxFrameBufferAcquiredBuffers >= 3) {
2524 nativeWindowSurface->preallocateBuffers();
2525 }
2526
2527 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002528 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2529 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002530 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002531 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002532 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002533 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002534 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002535 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002536 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002537 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002538 display->setLayerStack(state.layerStack);
2539 display->setProjection(state.orientation, state.viewport, state.frame);
2540 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002541
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002542 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002543}
2544
Lloyd Pique347200f2017-12-14 17:00:15 -08002545void SurfaceFlinger::processDisplayChangesLocked() {
2546 // here we take advantage of Vector's copy-on-write semantics to
2547 // improve performance by skipping the transaction entirely when
2548 // know that the lists are identical
2549 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2550 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2551 if (!curr.isIdenticalTo(draw)) {
2552 mVisibleRegionsDirty = true;
2553 const size_t cc = curr.size();
2554 size_t dc = draw.size();
2555
2556 // find the displays that were removed
2557 // (ie: in drawing state but not in current state)
2558 // also handle displays that changed
2559 // (ie: displays that are in both lists)
2560 for (size_t i = 0; i < dc;) {
2561 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2562 if (j < 0) {
2563 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002564 // Call makeCurrent() on the primary display so we can
2565 // be sure that nothing associated with this display
2566 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002567 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2568 defaultDisplay->makeCurrent();
2569 }
2570 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2571 display->disconnect(getHwComposer());
2572 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002573 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2574 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2575 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2576 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2577 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002578 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002579 } else {
2580 // this display is in both lists. see if something changed.
2581 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002582 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002583 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2584 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2585 if (state_binder != draw_binder) {
2586 // changing the surface is like destroying and
2587 // recreating the DisplayDevice, so we just remove it
2588 // from the drawing state, so that it get re-added
2589 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002590 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2591 display->disconnect(getHwComposer());
2592 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002593 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002594 mDrawingState.displays.removeItemsAt(i);
2595 dc--;
2596 // at this point we must loop to the next item
2597 continue;
2598 }
2599
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002600 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002601 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002602 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002603 }
2604 if ((state.orientation != draw[i].orientation) ||
2605 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002606 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002607 }
2608 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002609 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002610 }
2611 }
2612 }
2613 ++i;
2614 }
2615
2616 // find displays that were added
2617 // (ie: in current state but not in drawing state)
2618 for (size_t i = 0; i < cc; i++) {
2619 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2620 const DisplayDeviceState& state(curr[i]);
2621
2622 sp<DisplaySurface> dispSurface;
2623 sp<IGraphicBufferProducer> producer;
2624 sp<IGraphicBufferProducer> bqProducer;
2625 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002626 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002627
Dominik Laskowski7e045462018-05-30 13:02:02 -07002628 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002629 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002630 // Virtual displays without a surface are dormant:
2631 // they have external state (layer stack, projection,
2632 // etc.) but no internal state (i.e. a DisplayDevice).
2633 if (state.surface != nullptr) {
2634 // Allow VR composer to use virtual displays.
2635 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2636 int width = 0;
2637 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2638 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2639 int height = 0;
2640 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2641 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2642 int intFormat = 0;
2643 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2644 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002645 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002646
Dominik Laskowski7e045462018-05-30 13:02:02 -07002647 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2648 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002649 }
2650
2651 // TODO: Plumb requested format back up to consumer
2652
2653 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002654 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002655 bqProducer, bqConsumer,
2656 state.displayName);
2657
2658 dispSurface = vds;
2659 producer = vds;
2660 }
2661 } else {
2662 ALOGE_IF(state.surface != nullptr,
2663 "adding a supported display, but rendering "
2664 "surface is provided (%p), ignoring it",
2665 state.surface.get());
2666
Dominik Laskowski7e045462018-05-30 13:02:02 -07002667 displayId = state.type;
2668 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002669 producer = bqProducer;
2670 }
2671
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002672 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002673 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002674 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002675 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002676 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002677 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002678 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2679 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2680 true);
2681 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2682 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2683 true);
2684 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002685 }
2686 }
2687 }
2688 }
2689 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002690
2691 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002692}
2693
Mathias Agopian87baae12012-07-31 12:38:26 -07002694void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002695{
Dan Stoza7dde5992015-05-22 09:51:44 -07002696 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002697 mCurrentState.traverseInZOrder([](Layer* layer) {
2698 layer->notifyAvailableFrames();
2699 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002700
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002701 /*
2702 * Traversal of the children
2703 * (perform the transaction for each of them if needed)
2704 */
2705
Mathias Agopian3559b072012-08-15 13:46:03 -07002706 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002707 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002709 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002710
2711 const uint32_t flags = layer->doTransaction(0);
2712 if (flags & Layer::eVisibleRegion)
2713 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002714 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 }
2716
2717 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002718 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719 */
2720
Mathias Agopiane57f2922012-08-09 16:29:12 -07002721 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002722 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002723 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002724 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002726 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002727 // The transform hint might have changed for some layers
2728 // (either because a display has changed, or because a layer
2729 // as changed).
2730 //
2731 // Walk through all the layers in currentLayers,
2732 // and update their transform hint.
2733 //
2734 // If a layer is visible only on a single display, then that
2735 // display is used to calculate the hint, otherwise we use the
2736 // default display.
2737 //
2738 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2739 // the hint is set before we acquire a buffer from the surface texture.
2740 //
2741 // NOTE: layer transactions have taken place already, so we use their
2742 // drawing state. However, SurfaceFlinger's own transaction has not
2743 // happened yet, so we must use the current state layer list
2744 // (soon to become the drawing state list).
2745 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002746 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002747 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002748 bool first = true;
2749 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002750 // NOTE: we rely on the fact that layers are sorted by
2751 // layerStack first (so we don't have to traverse the list
2752 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002753 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002754 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002755 currentlayerStack = layerStack;
2756 // figure out if this layerstack is mirrored
2757 // (more than one display) if so, pick the default display,
2758 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002759 hintDisplay = nullptr;
2760 for (const auto& [token, display] : mDisplays) {
2761 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2762 if (hintDisplay) {
2763 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002764 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002765 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002766 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002767 }
2768 }
2769 }
2770 }
Chet Haase91d25932013-04-11 15:24:55 -07002771
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002772 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002773 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2774 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002775
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002776 // could be null when this layer is using a layerStack
2777 // that is not visible on any display. Also can occur at
2778 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002779 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002780 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002781
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002782 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002783 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002784 if (hintDisplay) {
2785 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002786 }
Robert Carr2047fae2016-11-28 14:09:09 -08002787
2788 first = false;
2789 });
Mathias Agopian84300952012-11-21 16:02:13 -08002790 }
2791
2792
Mathias Agopian3559b072012-08-15 13:46:03 -07002793 /*
2794 * Perform our own transaction if needed
2795 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002796
2797 if (mLayersAdded) {
2798 mLayersAdded = false;
2799 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002800 mVisibleRegionsDirty = true;
2801 }
2802
2803 // some layers might have been removed, so
2804 // we need to update the regions they're exposing.
2805 if (mLayersRemoved) {
2806 mLayersRemoved = false;
2807 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002808 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002809 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002810 // this layer is not visible anymore
2811 // TODO: we could traverse the tree from front to back and
2812 // compute the actual visible region
2813 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002814 Region visibleReg;
2815 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002816 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002817 }
Robert Carr2047fae2016-11-28 14:09:09 -08002818 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002819 }
2820
2821 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002822
2823 updateCursorAsync();
2824}
2825
2826void SurfaceFlinger::updateCursorAsync()
2827{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002828 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002829 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002830 continue;
2831 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002832
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002833 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2834 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002835 }
2836 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002837}
2838
2839void SurfaceFlinger::commitTransaction()
2840{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002841 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002842 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002843 for (const auto& l : mLayersPendingRemoval) {
2844 recordBufferingStats(l->getName().string(),
2845 l->getOccupancyHistory(true));
2846 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002847 }
2848 mLayersPendingRemoval.clear();
2849 }
2850
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002851 // If this transaction is part of a window animation then the next frame
2852 // we composite should be considered an animation as well.
2853 mAnimCompositionPending = mAnimTransactionPending;
2854
Mathias Agopian4fec8732012-06-29 14:12:52 -07002855 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002856 // clear the "changed" flags in current state
2857 mCurrentState.colorMatrixChanged = false;
2858
Robert Carr1f0a16a2016-10-24 16:27:39 -07002859 mDrawingState.traverseInZOrder([](Layer* layer) {
2860 layer->commitChildList();
2861 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002862 mTransactionPending = false;
2863 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002864 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865}
2866
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002867void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2868 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002869 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002870 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002871
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872 Region aboveOpaqueLayers;
2873 Region aboveCoveredLayers;
2874 Region dirty;
2875
Mathias Agopian87baae12012-07-31 12:38:26 -07002876 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877
Robert Carr2047fae2016-11-28 14:09:09 -08002878 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002880 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881
Jesse Hall01e29052013-02-19 16:13:35 -08002882 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002883 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002884 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002885 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002886
Mathias Agopianab028732010-03-16 16:41:46 -07002887 /*
2888 * opaqueRegion: area of a surface that is fully opaque.
2889 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002891
2892 /*
2893 * visibleRegion: area of a surface that is visible on screen
2894 * and not fully transparent. This is essentially the layer's
2895 * footprint minus the opaque regions above it.
2896 * Areas covered by a translucent surface are considered visible.
2897 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002899
2900 /*
2901 * coveredRegion: area of a surface that is covered by all
2902 * visible regions above it (which includes the translucent areas).
2903 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002904 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002905
Jesse Halla8026d22012-09-25 13:25:04 -07002906 /*
2907 * transparentRegion: area of a surface that is hinted to be completely
2908 * transparent. This is only used to tell when the layer has no visible
2909 * non-transparent regions and can be removed from the layer list. It
2910 * does not affect the visibleRegion of this layer or any layers
2911 * beneath it. The hint may not be correct if apps don't respect the
2912 * SurfaceView restrictions (which, sadly, some don't).
2913 */
2914 Region transparentRegion;
2915
Mathias Agopianab028732010-03-16 16:41:46 -07002916
2917 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002918 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002919 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002920 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002921 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002922 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002923 if (!visibleRegion.isEmpty()) {
2924 // Remove the transparent area from the visible region
2925 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002926 if (tr.preserveRects()) {
2927 // transform the transparent region
2928 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002929 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002930 // transformation too complex, can't do the
2931 // transparent region optimization.
2932 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002933 }
Mathias Agopianab028732010-03-16 16:41:46 -07002934 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935
Mathias Agopianab028732010-03-16 16:41:46 -07002936 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002937 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002938 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002939 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2940 // the opaque region is the layer's footprint
2941 opaqueRegion = visibleRegion;
2942 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943 }
2944 }
2945
Robert Carre5f4f692018-01-12 13:12:28 -08002946 if (visibleRegion.isEmpty()) {
2947 layer->clearVisibilityRegions();
2948 return;
2949 }
2950
Mathias Agopianab028732010-03-16 16:41:46 -07002951 // Clip the covered region to the visible region
2952 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2953
2954 // Update aboveCoveredLayers for next (lower) layer
2955 aboveCoveredLayers.orSelf(visibleRegion);
2956
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002957 // subtract the opaque region covered by the layers above us
2958 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002959
2960 // compute this layer's dirty region
2961 if (layer->contentDirty) {
2962 // we need to invalidate the whole region
2963 dirty = visibleRegion;
2964 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002965 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002966 layer->contentDirty = false;
2967 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002968 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002969 * the exposed region consists of two components:
2970 * 1) what's VISIBLE now and was COVERED before
2971 * 2) what's EXPOSED now less what was EXPOSED before
2972 *
2973 * note that (1) is conservative, we start with the whole
2974 * visible region but only keep what used to be covered by
2975 * something -- which mean it may have been exposed.
2976 *
2977 * (2) handles areas that were not covered by anything but got
2978 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002979 */
Mathias Agopianab028732010-03-16 16:41:46 -07002980 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002981 const Region oldVisibleRegion = layer->visibleRegion;
2982 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002983 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2984 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002985 }
2986 dirty.subtractSelf(aboveOpaqueLayers);
2987
2988 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002989 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002990
Mathias Agopianab028732010-03-16 16:41:46 -07002991 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002992 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002993
Jesse Halla8026d22012-09-25 13:25:04 -07002994 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002995 layer->setVisibleRegion(visibleRegion);
2996 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002997 layer->setVisibleNonTransparentRegion(
2998 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002999 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000
Mathias Agopian87baae12012-07-31 12:38:26 -07003001 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003002}
3003
Chia-I Wuab0c3192017-08-01 11:29:00 -07003004void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003005 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003006 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3007 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003008 }
3009 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003010}
3011
Dan Stoza6b9454d2014-11-07 16:00:59 -08003012bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003013{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003014 ALOGV("handlePageFlip");
3015
Brian Andersond6927fb2016-07-23 23:37:30 -07003016 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003017
Mathias Agopian4fec8732012-06-29 14:12:52 -07003018 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003019 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003020 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003021
3022 // Store the set of layers that need updates. This set must not change as
3023 // buffers are being latched, as this could result in a deadlock.
3024 // Example: Two producers share the same command stream and:
3025 // 1.) Layer 0 is latched
3026 // 2.) Layer 0 gets a new frame
3027 // 2.) Layer 1 gets a new frame
3028 // 3.) Layer 1 is latched.
3029 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3030 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003031 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003032 if (layer->hasQueuedFrame()) {
3033 frameQueued = true;
3034 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003035 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003036 } else {
3037 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003038 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003039 } else {
3040 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003041 }
Robert Carr2047fae2016-11-28 14:09:09 -08003042 });
3043
Dan Stoza9e56aa02015-11-02 13:00:03 -08003044 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07003045 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07003046 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003047 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003048 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003049 newDataLatched = true;
3050 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003051 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003052
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003053 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003054
3055 // If we will need to wake up at some time in the future to deal with a
3056 // queued frame that shouldn't be displayed during this vsync period, wake
3057 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003058 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003059 signalLayerUpdate();
3060 }
3061
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003062 // enter boot animation on first buffer latch
3063 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3064 ALOGI("Enter boot animation");
3065 mBootStage = BootStage::BOOTANIMATION;
3066 }
3067
Dan Stoza6b9454d2014-11-07 16:00:59 -08003068 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003069 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003070}
3071
Mathias Agopianad456f92011-01-13 17:53:01 -08003072void SurfaceFlinger::invalidateHwcGeometry()
3073{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003074 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003075}
3076
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003077void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3078 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003079 // We only need to actually compose the display if:
3080 // 1) It is being handled by hardware composer, which may need this to
3081 // keep its virtual display state machine in sync, or
3082 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003083 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003084 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003085 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003086 return;
3087 }
3088
Dan Stoza9e56aa02015-11-02 13:00:03 -08003089 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003090 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003091
3092 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003093 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003094}
3095
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003096bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003097 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003099 const Region bounds(display->bounds());
3100 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003101 const auto displayId = display->getId();
3102 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003103 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003104
Chia-I Wu8e50e692018-05-04 10:12:37 -07003105 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003106 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003107
Dan Stoza9e56aa02015-11-02 13:00:03 -08003108 if (hasClientComposition) {
3109 ALOGV("hasClientComposition");
3110
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003111 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003112 if (display->hasWideColorGamut()) {
3113 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003114 }
3115 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003116 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003117 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003118
Dominik Laskowski7e045462018-05-30 13:02:02 -07003119 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003120 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3121 HWC2::Capability::SkipClientColorTransform);
3122
Chia-I Wud49d6692018-06-27 07:17:41 +08003123 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003124 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3125 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003126 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003127 }
3128
Chia-I Wud49d6692018-06-27 07:17:41 +08003129 // The current enhanced saturation matrix is designed to enhance Display P3,
3130 // thus we only apply this matrix when the render intent is not colorimetric
3131 // and the output color space is Display P3.
3132 needsEnhancedColorMatrix =
3133 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3134 outputDataspace == Dataspace::DISPLAY_P3);
3135 if (needsEnhancedColorMatrix) {
3136 colorMatrix *= mEnhancedSaturationMatrix;
3137 }
3138
3139 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003140
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003141 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003142 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003143 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003144 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003145
3146 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003147 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3148 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3149 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003150 }
3151 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003152 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003153
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003154 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003155 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003156 // when using overlays, we assume a fully transparent framebuffer
3157 // NOTE: we could reduce how much we need to clear, for instance
3158 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003159 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003160 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003161 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003162 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003163 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003164 // we're left with the letterbox region
3165 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003166 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003167
3168 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003169 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003170
Mathias Agopianb9494d52012-04-18 02:28:45 -07003171 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003172 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003173 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003174 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003175 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003176 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003177
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003178 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003179 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003180 // scissor on the main display. It should never be needed
3181 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003182 const Rect& bounds = display->getBounds();
3183 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07003184 if (scissor != bounds) {
3185 // scissor doesn't match the screen's dimensions, so we
3186 // need to clear everything outside of it and enable
3187 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003188
Mathias Agopianf45c5102012-10-24 16:29:17 -07003189 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003190 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003191 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003192 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003193 }
3194 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003195 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003196
Mathias Agopian85d751c2012-08-29 16:59:24 -07003197 /*
3198 * and then, render the layers targeted at the framebuffer
3199 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003200
Dan Stoza9e56aa02015-11-02 13:00:03 -08003201 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003202 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003203 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003204 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003205 const Region clip(bounds.intersect(
3206 displayTransform.transform(layer->visibleRegion)));
3207 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003208 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003209 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003210 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003211 case HWC2::Composition::Cursor:
3212 case HWC2::Composition::Device:
3213 case HWC2::Composition::Sideband:
3214 case HWC2::Composition::SolidColor: {
3215 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003216 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05303217 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3218 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003219 // never clear the very first layer since we're
3220 // guaranteed the FB is already cleared
3221 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003222 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003223 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003224 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003225 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003226 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003227 break;
3228 }
3229 default:
3230 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003231 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003232 } else {
3233 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003234 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003235 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003236 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003237
Chia-I Wud49d6692018-06-27 07:17:41 +08003238 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003239 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003240 }
3241
Mathias Agopianf45c5102012-10-24 16:29:17 -07003242 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003243 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003244 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003245}
3246
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003247void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3248 const Region& region) const {
3249 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003250 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003251 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252}
3253
Dan Stoza7d89d062015-04-30 13:29:25 -07003254status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003255 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003256 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003257 const sp<Layer>& lbc,
3258 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003259{
Dan Stoza7d89d062015-04-30 13:29:25 -07003260 // add this layer to the current state list
3261 {
3262 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003263 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003264 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3265 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003266 return NO_MEMORY;
3267 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003268 if (parent == nullptr) {
3269 mCurrentState.layersSortedByZ.add(lbc);
3270 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003271 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003272 ALOGE("addClientLayer called with a removed parent");
3273 return NAME_NOT_FOUND;
3274 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003275 parent->addChild(lbc);
3276 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003277
Yiwei Zhang243b3782018-05-15 17:40:04 -07003278 if (gbc != nullptr) {
3279 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3280 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3281 mMaxGraphicBufferProducerListSize,
3282 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3283 mGraphicBufferProducerList.size(),
3284 mMaxGraphicBufferProducerListSize, mNumLayers);
3285 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003286 mLayersAdded = true;
3287 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003288 }
3289
Mathias Agopian96f08192010-06-02 23:28:45 -07003290 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003291 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003292
Dan Stoza7d89d062015-04-30 13:29:25 -07003293 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003294}
3295
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003296status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003297 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003298 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3299}
Robert Carr7f9b8992017-03-10 11:08:39 -08003300
chaviwca27f252018-02-06 16:46:39 -08003301status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3302 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003303 if (layer->isPendingRemoval()) {
3304 return NO_ERROR;
3305 }
3306
Robert Carr1f0a16a2016-10-24 16:27:39 -07003307 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003308 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003309 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003310 if (topLevelOnly) {
3311 return NO_ERROR;
3312 }
3313
Chia-I Wu98f1c102017-05-30 14:54:08 -07003314 sp<Layer> ancestor = p;
3315 while (ancestor->getParent() != nullptr) {
3316 ancestor = ancestor->getParent();
3317 }
3318 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3319 ALOGE("removeLayer called with a layer whose parent has been removed");
3320 return NAME_NOT_FOUND;
3321 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003322
3323 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003324 } else {
3325 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003326 }
3327
Robert Carr136e2f62017-02-08 17:54:29 -08003328 // As a matter of normal operation, the LayerCleaner will produce a second
3329 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3330 // so we will succeed in promoting it, but it's already been removed
3331 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3332 // otherwise something has gone wrong and we are leaking the layer.
3333 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003334 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3335 layer->getName().string(),
3336 (p != nullptr) ? p->getName().string() : "no-parent");
3337 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003338 } else if (index < 0) {
3339 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003340 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003341
Chia-I Wuc6657022017-08-15 11:18:17 -07003342 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003343 mLayersPendingRemoval.add(layer);
3344 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003345 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003346 setTransactionFlags(eTransactionNeeded);
3347 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003348}
3349
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003350uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003351 return android_atomic_release_load(&mTransactionFlags);
3352}
3353
Mathias Agopian3f844832013-08-07 21:24:32 -07003354uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003355 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3356}
3357
Mathias Agopian3f844832013-08-07 21:24:32 -07003358uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003359 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3360}
3361
3362uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3363 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003364 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003365 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003366 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003367 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003368 }
3369 return old;
3370}
3371
chaviwca27f252018-02-06 16:46:39 -08003372bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3373 for (const ComposerState& state : states) {
3374 // Here we need to check that the interface we're given is indeed
3375 // one of our own. A malicious client could give us a nullptr
3376 // IInterface, or one of its own or even one of our own but a
3377 // different type. All these situations would cause us to crash.
3378 if (state.client == nullptr) {
3379 return true;
3380 }
3381
3382 sp<IBinder> binder = IInterface::asBinder(state.client);
3383 if (binder == nullptr) {
3384 return true;
3385 }
3386
3387 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3388 return true;
3389 }
3390 }
3391 return false;
3392}
3393
Mathias Agopian8b33f032012-07-24 20:43:54 -07003394void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003395 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003396 const Vector<DisplayState>& displays,
3397 uint32_t flags)
3398{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003399 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003400 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003401 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003402
chaviwca27f252018-02-06 16:46:39 -08003403 if (containsAnyInvalidClientState(states)) {
3404 return;
3405 }
3406
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003407 if (flags & eAnimation) {
3408 // For window updates that are part of an animation we must wait for
3409 // previous animation "frames" to be handled.
3410 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003411 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003412 if (CC_UNLIKELY(err != NO_ERROR)) {
3413 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003414 // caller after a few seconds.
3415 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3416 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003417 mAnimTransactionPending = false;
3418 break;
3419 }
3420 }
3421 }
3422
chaviwca27f252018-02-06 16:46:39 -08003423 for (const DisplayState& display : displays) {
3424 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003425 }
3426
chaviwca27f252018-02-06 16:46:39 -08003427 for (const ComposerState& state : states) {
3428 transactionFlags |= setClientStateLocked(state);
3429 }
3430
3431 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3432 // as destroyed should only occur after setting all other states. This is to allow for a
3433 // child re-parent to happen before marking its original parent as destroyed (which would
3434 // then mark the child as destroyed).
3435 for (const ComposerState& state : states) {
3436 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003437 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003438
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003439 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3440 // anyway. This can be used as a flush mechanism for previous async transactions.
3441 // Empty animation transaction can be used to simulate back-pressure, so also force a
3442 // transaction for empty animation transactions.
3443 if (transactionFlags == 0 &&
3444 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003445 transactionFlags = eTransactionNeeded;
3446 }
3447
Mathias Agopian386aa982011-11-07 21:58:03 -08003448 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003449 if (mInterceptor->isEnabled()) {
3450 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003451 }
Irvel468051e2016-06-13 16:44:44 -07003452
Mathias Agopian386aa982011-11-07 21:58:03 -08003453 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003454 const auto start = (flags & eEarlyWakeup)
3455 ? VSyncModulator::TransactionStart::EARLY
3456 : VSyncModulator::TransactionStart::NORMAL;
3457 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003458
3459 // if this is a synchronous transaction, wait for it to take effect
3460 // before returning.
3461 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003462 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003463 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003464 if (flags & eAnimation) {
3465 mAnimTransactionPending = true;
3466 }
3467 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003468 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3469 if (CC_UNLIKELY(err != NO_ERROR)) {
3470 // just in case something goes wrong in SF, return to the
3471 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003472 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3473 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003474 break;
3475 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003476 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003477 }
3478}
3479
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003480uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3481 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3482 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003483
Mathias Agopiane57f2922012-08-09 16:29:12 -07003484 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003485 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3486
3487 const uint32_t what = s.what;
3488 if (what & DisplayState::eSurfaceChanged) {
3489 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3490 state.surface = s.surface;
3491 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003492 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003493 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003494 if (what & DisplayState::eLayerStackChanged) {
3495 if (state.layerStack != s.layerStack) {
3496 state.layerStack = s.layerStack;
3497 flags |= eDisplayTransactionNeeded;
3498 }
3499 }
3500 if (what & DisplayState::eDisplayProjectionChanged) {
3501 if (state.orientation != s.orientation) {
3502 state.orientation = s.orientation;
3503 flags |= eDisplayTransactionNeeded;
3504 }
3505 if (state.frame != s.frame) {
3506 state.frame = s.frame;
3507 flags |= eDisplayTransactionNeeded;
3508 }
3509 if (state.viewport != s.viewport) {
3510 state.viewport = s.viewport;
3511 flags |= eDisplayTransactionNeeded;
3512 }
3513 }
3514 if (what & DisplayState::eDisplaySizeChanged) {
3515 if (state.width != s.width) {
3516 state.width = s.width;
3517 flags |= eDisplayTransactionNeeded;
3518 }
3519 if (state.height != s.height) {
3520 state.height = s.height;
3521 flags |= eDisplayTransactionNeeded;
3522 }
3523 }
3524
Mathias Agopiane57f2922012-08-09 16:29:12 -07003525 return flags;
3526}
3527
Robert Carrd4ae7f32018-06-07 16:10:57 -07003528bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3529 IPCThreadState* ipc = IPCThreadState::self();
3530 const int pid = ipc->getCallingPid();
3531 const int uid = ipc->getCallingUid();
3532
3533 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3534 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3535 return false;
3536 }
3537 return true;
3538}
3539
chaviwca27f252018-02-06 16:46:39 -08003540uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3541 const layer_state_t& s = composerState.state;
3542 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3543
Mathias Agopian13127d82013-03-05 17:47:11 -08003544 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003545 if (layer == nullptr) {
3546 return 0;
3547 }
3548
3549 if (layer->isPendingRemoval()) {
3550 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3551 return 0;
3552 }
3553
3554 uint32_t flags = 0;
3555
3556 const uint32_t what = s.what;
3557 bool geometryAppliesWithResize =
3558 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003559
3560 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3561 // pending state will also be deferred.
3562 if (what & layer_state_t::eDeferTransaction) {
3563 layer->pushPendingState();
3564 }
3565
chaviw8b3871a2017-11-01 17:41:01 -07003566 if (what & layer_state_t::ePositionChanged) {
3567 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3568 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003569 }
chaviw8b3871a2017-11-01 17:41:01 -07003570 }
3571 if (what & layer_state_t::eLayerChanged) {
3572 // NOTE: index needs to be calculated before we update the state
3573 const auto& p = layer->getParent();
3574 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003575 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003576 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003577 mCurrentState.layersSortedByZ.removeAt(idx);
3578 mCurrentState.layersSortedByZ.add(layer);
3579 // we need traversal (state changed)
3580 // AND transaction (list changed)
3581 flags |= eTransactionNeeded|eTraversalNeeded;
3582 }
chaviw8b3871a2017-11-01 17:41:01 -07003583 } else {
3584 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003585 flags |= eTransactionNeeded|eTraversalNeeded;
3586 }
3587 }
chaviw8b3871a2017-11-01 17:41:01 -07003588 }
3589 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003590 // NOTE: index needs to be calculated before we update the state
3591 const auto& p = layer->getParent();
3592 if (p == nullptr) {
3593 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3594 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3595 mCurrentState.layersSortedByZ.removeAt(idx);
3596 mCurrentState.layersSortedByZ.add(layer);
3597 // we need traversal (state changed)
3598 // AND transaction (list changed)
3599 flags |= eTransactionNeeded|eTraversalNeeded;
3600 }
3601 } else {
3602 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3603 flags |= eTransactionNeeded|eTraversalNeeded;
3604 }
chaviw8b3871a2017-11-01 17:41:01 -07003605 }
3606 }
3607 if (what & layer_state_t::eSizeChanged) {
3608 if (layer->setSize(s.w, s.h)) {
3609 flags |= eTraversalNeeded;
3610 }
3611 }
3612 if (what & layer_state_t::eAlphaChanged) {
3613 if (layer->setAlpha(s.alpha))
3614 flags |= eTraversalNeeded;
3615 }
3616 if (what & layer_state_t::eColorChanged) {
3617 if (layer->setColor(s.color))
3618 flags |= eTraversalNeeded;
3619 }
3620 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003621 // TODO: b/109894387
3622 //
3623 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3624 // rotation. To see the problem observe that if we have a square parent, and a child
3625 // of the same size, then we rotate the child 45 degrees around it's center, the child
3626 // must now be cropped to a non rectangular 8 sided region.
3627 //
3628 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3629 // private API, and the WindowManager only uses rotation in one case, which is on a top
3630 // level layer in which cropping is not an issue.
3631 //
3632 // However given that abuse of rotation matrices could lead to surfaces extending outside
3633 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3634 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3635 // transformations.
3636 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003637 flags |= eTraversalNeeded;
3638 }
3639 if (what & layer_state_t::eTransparentRegionChanged) {
3640 if (layer->setTransparentRegionHint(s.transparentRegion))
3641 flags |= eTraversalNeeded;
3642 }
3643 if (what & layer_state_t::eFlagsChanged) {
3644 if (layer->setFlags(s.flags, s.mask))
3645 flags |= eTraversalNeeded;
3646 }
3647 if (what & layer_state_t::eCropChanged) {
3648 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3649 flags |= eTraversalNeeded;
3650 }
3651 if (what & layer_state_t::eFinalCropChanged) {
3652 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3653 flags |= eTraversalNeeded;
3654 }
3655 if (what & layer_state_t::eLayerStackChanged) {
3656 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3657 // We only allow setting layer stacks for top level layers,
3658 // everything else inherits layer stack from its parent.
3659 if (layer->hasParent()) {
3660 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3661 layer->getName().string());
3662 } else if (idx < 0) {
3663 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3664 "that also does not appear in the top level layer list. Something"
3665 " has gone wrong.", layer->getName().string());
3666 } else if (layer->setLayerStack(s.layerStack)) {
3667 mCurrentState.layersSortedByZ.removeAt(idx);
3668 mCurrentState.layersSortedByZ.add(layer);
3669 // we need traversal (state changed)
3670 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003671 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003672 }
3673 }
3674 if (what & layer_state_t::eDeferTransaction) {
3675 if (s.barrierHandle != nullptr) {
3676 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3677 } else if (s.barrierGbp != nullptr) {
3678 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3679 if (authenticateSurfaceTextureLocked(gbp)) {
3680 const auto& otherLayer =
3681 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3682 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3683 } else {
3684 ALOGE("Attempt to defer transaction to to an"
3685 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003686 }
3687 }
chaviw8b3871a2017-11-01 17:41:01 -07003688 // We don't trigger a traversal here because if no other state is
3689 // changed, we don't want this to cause any more work
3690 }
3691 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003692 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003693 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003694 if (!hadParent) {
3695 mCurrentState.layersSortedByZ.remove(layer);
3696 }
chaviw8b3871a2017-11-01 17:41:01 -07003697 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003698 }
chaviw8b3871a2017-11-01 17:41:01 -07003699 }
3700 if (what & layer_state_t::eReparentChildren) {
3701 if (layer->reparentChildren(s.reparentHandle)) {
3702 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003703 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003704 }
chaviw8b3871a2017-11-01 17:41:01 -07003705 if (what & layer_state_t::eDetachChildren) {
3706 layer->detachChildren();
3707 }
3708 if (what & layer_state_t::eOverrideScalingModeChanged) {
3709 layer->setOverrideScalingMode(s.overrideScalingMode);
3710 // We don't trigger a traversal here because if no other state is
3711 // changed, we don't want this to cause any more work
3712 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003713 return flags;
3714}
3715
chaviwca27f252018-02-06 16:46:39 -08003716void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3717 const layer_state_t& state = composerState.state;
3718 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3719
3720 sp<Layer> layer(client->getLayerUser(state.surface));
3721 if (layer == nullptr) {
3722 return;
3723 }
3724
3725 if (layer->isPendingRemoval()) {
3726 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3727 return;
3728 }
3729
3730 if (state.what & layer_state_t::eDestroySurface) {
3731 removeLayerLocked(mStateLock, layer);
3732 }
3733}
3734
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003735status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003736 const String8& name,
3737 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003738 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003739 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003740 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003741{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003742 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003743 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003744 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003745 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003746 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003747
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003748 status_t result = NO_ERROR;
3749
3750 sp<Layer> layer;
3751
Cody Northropbc755282017-03-31 12:00:08 -06003752 String8 uniqueName = getUniqueLayerName(name);
3753
Mathias Agopian3165cc22012-08-08 19:42:09 -07003754 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3755 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003756 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003757 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003758 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003759
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003760 break;
chaviw13fdc492017-06-27 12:40:18 -07003761 case ISurfaceComposerClient::eFXSurfaceColor:
3762 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003763 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003764 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003765 break;
3766 default:
3767 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003768 break;
3769 }
3770
Dan Stoza7d89d062015-04-30 13:29:25 -07003771 if (result != NO_ERROR) {
3772 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003773 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003774
Chia-I Wuab0c3192017-08-01 11:29:00 -07003775 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3776 // TODO b/64227542
3777 if (windowType == 441731) {
3778 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3779 layer->setPrimaryDisplayOnly();
3780 }
3781
Albert Chaulk479c60c2017-01-27 14:21:34 -05003782 layer->setInfo(windowType, ownerUid);
3783
Robert Carr1f0a16a2016-10-24 16:27:39 -07003784 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003785 if (result != NO_ERROR) {
3786 return result;
3787 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003788 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003789
3790 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003791 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003792}
3793
Cody Northropbc755282017-03-31 12:00:08 -06003794String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3795{
3796 bool matchFound = true;
3797 uint32_t dupeCounter = 0;
3798
3799 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3800 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3801
Dan Stoza436ccf32018-06-21 12:10:12 -07003802 // Grab the state lock since we're accessing mCurrentState
3803 Mutex::Autolock lock(mStateLock);
3804
Cody Northropbc755282017-03-31 12:00:08 -06003805 // Loop over layers until we're sure there is no matching name
3806 while (matchFound) {
3807 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003808 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003809 if (layer->getName() == uniqueName) {
3810 matchFound = true;
3811 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3812 }
3813 });
3814 }
3815
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003816 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3817 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003818
3819 return uniqueName;
3820}
3821
David Sodman0c69cad2017-08-21 12:12:51 -07003822status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003823 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3824 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003825{
3826 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003827 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003828 case PIXEL_FORMAT_TRANSPARENT:
3829 case PIXEL_FORMAT_TRANSLUCENT:
3830 format = PIXEL_FORMAT_RGBA_8888;
3831 break;
3832 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003833 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003834 break;
3835 }
3836
David Sodman0c69cad2017-08-21 12:12:51 -07003837 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3838 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003839 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003840 *handle = layer->getHandle();
3841 *gbp = layer->getProducer();
3842 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003843 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003844
David Sodman0c69cad2017-08-21 12:12:51 -07003845 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003846 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003847}
3848
chaviw13fdc492017-06-27 12:40:18 -07003849status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003850 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003851 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003852{
chaviw13fdc492017-06-27 12:40:18 -07003853 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003854 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003855 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003856}
3857
Mathias Agopianac9fa422013-02-11 16:40:36 -08003858status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003859{
Robert Carr9524cb32017-02-13 11:32:32 -08003860 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003861 status_t err = NO_ERROR;
3862 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003863 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003864 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003865 err = removeLayer(l);
3866 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3867 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003868 }
3869 return err;
3870}
3871
Mathias Agopian13127d82013-03-05 17:47:11 -08003872status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003873{
Mathias Agopian67106042013-03-14 19:18:13 -07003874 // called by ~LayerCleaner() when all references to the IBinder (handle)
3875 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003876 sp<Layer> l = layer.promote();
3877 if (l == nullptr) {
3878 // The layer has already been removed, carry on
3879 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003880 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003881 // If we have a parent, then we can continue to live as long as it does.
3882 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003883}
3884
Mathias Agopianb60314a2012-04-10 22:09:54 -07003885// ---------------------------------------------------------------------------
3886
Andy McFadden13a082e2012-08-24 10:16:42 -07003887void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003888 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3889 if (!displayToken) return;
3890
Jesse Hall01e29052013-02-19 16:13:35 -08003891 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003892 Vector<ComposerState> state;
3893 Vector<DisplayState> displays;
3894 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003895 d.what = DisplayState::eDisplayProjectionChanged |
3896 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003897 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003898 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003899 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003900 d.frame.makeInvalid();
3901 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003902 d.width = 0;
3903 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003904 displays.add(d);
3905 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003906
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003907 const auto display = getDisplayDevice(displayToken);
3908 if (!display) return;
3909
3910 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3911
3912 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003913 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003914 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003915
Brian Andersond0010582017-03-07 13:20:31 -08003916 // Use phase of 0 since phase is not known.
3917 // Use latency of 0, which will snap to the ideal latency.
3918 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003919}
3920
3921void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003922 // Async since we may be called from the main thread.
3923 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003924}
3925
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003926void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3927 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003928 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003929 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003930
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003931 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003932 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003933 return;
3934 }
3935
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003936 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003937 ALOGW("Trying to set power mode for virtual display");
3938 return;
3939 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003940
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003941 display->setPowerMode(mode);
3942
Lloyd Pique4dccc412018-01-22 17:21:36 -08003943 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003944 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003945 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003946 if (idx < 0) {
3947 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3948 return;
3949 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003950 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003951 }
3952
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003953 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003954 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003955 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003956 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003957 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003958 // FIXME: eventthread only knows about the main display right now
3959 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003960 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003961 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003962
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003963 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003964 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003965 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003966
3967 struct sched_param param = {0};
3968 param.sched_priority = 1;
3969 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3970 ALOGW("Couldn't set SCHED_FIFO on display on");
3971 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003972 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003973 // Turn off the display
3974 struct sched_param param = {0};
3975 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3976 ALOGW("Couldn't set SCHED_OTHER on display off");
3977 }
3978
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003979 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003980 disableHardwareVsync(true); // also cancels any in-progress resync
3981
Mathias Agopiancde87a32012-09-13 14:09:01 -07003982 // FIXME: eventthread only knows about the main display right now
3983 mEventThread->onScreenReleased();
3984 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003985
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003986 getHwComposer().setPowerMode(type, mode);
3987 mVisibleRegionsDirty = true;
3988 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003989 } else if (mode == HWC_POWER_MODE_DOZE ||
3990 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003991 // Update display while dozing
3992 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003993 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003994 // FIXME: eventthread only knows about the main display right now
3995 mEventThread->onScreenAcquired();
3996 resyncToHardwareVsync(true);
3997 }
3998 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3999 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004000 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004001 disableHardwareVsync(true); // also cancels any in-progress resync
4002 // FIXME: eventthread only knows about the main display right now
4003 mEventThread->onScreenReleased();
4004 }
4005 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004006 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004007 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004008 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004009 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004010
4011 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004012}
4013
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004014void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004015 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004016 const auto display = getDisplayDevice(displayToken);
4017 if (!display) {
4018 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4019 displayToken.get());
4020 } else if (display->isVirtual()) {
4021 ALOGW("Attempt to set power mode %d for virtual display", mode);
4022 } else {
4023 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004024 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004025 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004026}
4027
4028// ---------------------------------------------------------------------------
4029
Lloyd Pique755e3192018-01-31 16:46:15 -08004030status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4031 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004032 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004033
Mathias Agopianbd115332013-04-18 16:41:04 -07004034 IPCThreadState* ipc = IPCThreadState::self();
4035 const int pid = ipc->getCallingPid();
4036 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004037
Mathias Agopianbd115332013-04-18 16:41:04 -07004038 if ((uid != AID_SHELL) &&
4039 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004040 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004041 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004042 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004043 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004044 // (this would indicate SF is stuck, but we want to be able to
4045 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004046 status_t err = mStateLock.timedLock(s2ns(1));
4047 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004048 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004049 result.appendFormat(
4050 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4051 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004052 }
4053
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004054 bool dumpAll = true;
4055 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004056 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004057
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004058 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004059 if ((index < numArgs) &&
4060 (args[index] == String16("--list"))) {
4061 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004062 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004063 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004064 }
4065
4066 if ((index < numArgs) &&
4067 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004068 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004069 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004070 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004071 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004072
4073 if ((index < numArgs) &&
4074 (args[index] == String16("--latency-clear"))) {
4075 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004076 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004077 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004078 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004079
4080 if ((index < numArgs) &&
4081 (args[index] == String16("--dispsync"))) {
4082 index++;
4083 mPrimaryDispSync.dump(result);
4084 dumpAll = false;
4085 }
Dan Stozab90cf072015-03-05 11:05:59 -08004086
4087 if ((index < numArgs) &&
4088 (args[index] == String16("--static-screen"))) {
4089 index++;
4090 dumpStaticScreenStats(result);
4091 dumpAll = false;
4092 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004093
4094 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004095 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004096 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004097 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004098 dumpAll = false;
4099 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004100
4101 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4102 index++;
4103 dumpWideColorInfo(result);
4104 dumpAll = false;
4105 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004106
4107 if ((index < numArgs) &&
4108 (args[index] == String16("--enable-layer-stats"))) {
4109 index++;
4110 mLayerStats.enable();
4111 dumpAll = false;
4112 }
4113
4114 if ((index < numArgs) &&
4115 (args[index] == String16("--disable-layer-stats"))) {
4116 index++;
4117 mLayerStats.disable();
4118 dumpAll = false;
4119 }
4120
4121 if ((index < numArgs) &&
4122 (args[index] == String16("--clear-layer-stats"))) {
4123 index++;
4124 mLayerStats.clear();
4125 dumpAll = false;
4126 }
4127
4128 if ((index < numArgs) &&
4129 (args[index] == String16("--dump-layer-stats"))) {
4130 index++;
4131 mLayerStats.dump(result);
4132 dumpAll = false;
4133 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004134
4135 if ((index < numArgs) &&
4136 (args[index] == String16("--display-identification"))) {
4137 index++;
4138 dumpDisplayIdentificationData(result);
4139 dumpAll = false;
4140 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004141
4142 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4143 index++;
4144 mTimeStats.parseArgs(asProto, args, index, result);
4145 dumpAll = false;
4146 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004147 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004148
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004149 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004150 if (asProto) {
4151 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4152 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4153 } else {
4154 dumpAllLocked(args, index, result);
4155 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004156 }
4157
Mathias Agopian9795c422009-08-26 16:36:26 -07004158 if (locked) {
4159 mStateLock.unlock();
4160 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004161 }
4162 write(fd, result.string(), result.size());
4163 return NO_ERROR;
4164}
4165
Dan Stozac7014012014-02-14 15:03:43 -08004166void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4167 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004168{
Robert Carr2047fae2016-11-28 14:09:09 -08004169 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004170 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004171 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004172}
4173
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004174void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004175 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004176{
4177 String8 name;
4178 if (index < args.size()) {
4179 name = String8(args[index]);
4180 index++;
4181 }
4182
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004183 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4184 getHwComposer().isConnected(displayId)) {
4185 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4186 const nsecs_t period = activeConfig->getVsyncPeriod();
4187 result.appendFormat("%" PRId64 "\n", period);
4188 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004189
4190 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004191 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004192 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004193 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004194 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004195 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004196 }
Robert Carr2047fae2016-11-28 14:09:09 -08004197 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004198 }
4199}
4200
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004201void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004202 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004203{
4204 String8 name;
4205 if (index < args.size()) {
4206 name = String8(args[index]);
4207 index++;
4208 }
4209
Robert Carr2047fae2016-11-28 14:09:09 -08004210 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004211 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004212 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004213 }
Robert Carr2047fae2016-11-28 14:09:09 -08004214 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004215
Svetoslavd85084b2014-03-20 10:28:31 -07004216 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004217}
4218
Jamie Gennis6547ff42013-07-16 20:12:42 -07004219// This should only be called from the main thread. Otherwise it would need
4220// the lock and should use mCurrentState rather than mDrawingState.
4221void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004222 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004223 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004224 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004225
4226 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4227}
4228
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004229void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004230{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004231 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004232
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004233 if (isLayerTripleBufferingDisabled())
4234 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004235
4236 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004237 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004238 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004239 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004240 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4241 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004242 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004243}
4244
Dan Stozab90cf072015-03-05 11:05:59 -08004245void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4246{
4247 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004248 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4249 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004250 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004251 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004252 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4253 b + 1, bucketTimeSec, percent);
4254 }
David Sodman4a36e932017-11-07 14:29:47 -08004255 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004256 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004257 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004258 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004259 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004260}
4261
Dan Stozae77c7662016-05-13 11:37:28 -07004262void SurfaceFlinger::recordBufferingStats(const char* layerName,
4263 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004264 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4265 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004266 for (const auto& segment : history) {
4267 if (!segment.usedThirdBuffer) {
4268 stats.twoBufferTime += segment.totalTime;
4269 }
4270 if (segment.occupancyAverage < 1.0f) {
4271 stats.doubleBufferedTime += segment.totalTime;
4272 } else if (segment.occupancyAverage < 2.0f) {
4273 stats.tripleBufferedTime += segment.totalTime;
4274 }
4275 ++stats.numSegments;
4276 stats.totalTime += segment.totalTime;
4277 }
4278}
4279
Brian Andersond6927fb2016-07-23 23:37:30 -07004280void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4281 result.appendFormat("Layer frame timestamps:\n");
4282
4283 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4284 const size_t count = currentLayers.size();
4285 for (size_t i=0 ; i<count ; i++) {
4286 currentLayers[i]->dumpFrameEvents(result);
4287 }
4288}
4289
Dan Stozae77c7662016-05-13 11:37:28 -07004290void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4291 result.append("Buffering stats:\n");
4292 result.append(" [Layer name] <Active time> <Two buffer> "
4293 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004294 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004295 typedef std::tuple<std::string, float, float, float> BufferTuple;
4296 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004297 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004298 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004299 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004300 if (stats.numSegments == 0) {
4301 continue;
4302 }
4303 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4304 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4305 stats.totalTime;
4306 float doubleBufferRatio = static_cast<float>(
4307 stats.doubleBufferedTime) / stats.totalTime;
4308 float tripleBufferRatio = static_cast<float>(
4309 stats.tripleBufferedTime) / stats.totalTime;
4310 sorted.insert({activeTime, {name, twoBufferRatio,
4311 doubleBufferRatio, tripleBufferRatio}});
4312 }
4313 for (const auto& sortedPair : sorted) {
4314 float activeTime = sortedPair.first;
4315 const BufferTuple& values = sortedPair.second;
4316 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4317 std::get<0>(values).c_str(), activeTime,
4318 std::get<1>(values), std::get<2>(values),
4319 std::get<3>(values));
4320 }
4321 result.append("\n");
4322}
4323
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004324void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004325 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004326 const int32_t displayId = display->getId();
4327 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4328 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004329 continue;
4330 }
4331
Dominik Laskowski7e045462018-05-30 13:02:02 -07004332 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004333 uint8_t port;
4334 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004335 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004336 result.append("no identification data\n");
4337 continue;
4338 }
4339
4340 if (!isEdid(data)) {
4341 result.append("unknown identification data: ");
4342 for (uint8_t byte : data) {
4343 result.appendFormat("%x ", byte);
4344 }
4345 result.append("\n");
4346 continue;
4347 }
4348
4349 const auto edid = parseEdid(data);
4350 if (!edid) {
4351 result.append("invalid EDID: ");
4352 for (uint8_t byte : data) {
4353 result.appendFormat("%x ", byte);
4354 }
4355 result.append("\n");
4356 continue;
4357 }
4358
4359 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4360 result.append(edid->displayName.data(), edid->displayName.length());
4361 result.append("\"\n");
4362 }
4363 result.append("\n");
4364}
4365
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004366void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4367 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004368 result.appendFormat("DisplayColorSetting: %s\n",
4369 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004370
4371 // TODO: print out if wide-color mode is active or not
4372
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004373 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004374 const int32_t displayId = display->getId();
4375 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004376 continue;
4377 }
4378
Dominik Laskowski7e045462018-05-30 13:02:02 -07004379 result.appendFormat("Display %d color modes:\n", displayId);
4380 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004381 for (auto&& mode : modes) {
4382 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4383 }
4384
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004385 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004386 result.appendFormat(" Current color mode: %s (%d)\n",
4387 decodeColorMode(currentMode).c_str(), currentMode);
4388 }
4389 result.append("\n");
4390}
4391
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004392LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004393 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004394 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4395 const State& state = useDrawing ? mDrawingState : mCurrentState;
4396 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004397 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004398 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004399 });
4400
4401 return layersProto;
4402}
4403
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004404LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004405 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004406
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004407 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004408 resolution->set_w(display.getWidth());
4409 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004410
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004411 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4412 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4413 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004414
Dominik Laskowski7e045462018-05-30 13:02:02 -07004415 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004416 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004417 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004418 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004419 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004420 }
4421 });
4422
4423 return layersProto;
4424}
4425
Mathias Agopian74d211a2013-04-22 16:55:35 +02004426void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4427 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004428{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004429 bool colorize = false;
4430 if (index < args.size()
4431 && (args[index] == String16("--color"))) {
4432 colorize = true;
4433 index++;
4434 }
4435
4436 Colorizer colorizer(colorize);
4437
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004438 // figure out if we're stuck somewhere
4439 const nsecs_t now = systemTime();
4440 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4441 const nsecs_t inTransaction(mDebugInTransaction);
4442 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4443 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4444
4445 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004446 * Dump library configuration.
4447 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004448
4449 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004450 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004451 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004452 appendSfConfigString(result);
4453 appendUiConfigString(result);
4454 appendGuiConfigString(result);
4455 result.append("\n");
4456
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004457 result.append("\nDisplay identification data:\n");
4458 dumpDisplayIdentificationData(result);
4459
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004460 result.append("\nWide-Color information:\n");
4461 dumpWideColorInfo(result);
4462
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004463 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004464 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004465 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004466 result.append(SyncFeatures::getInstance().toString());
4467 result.append("\n");
4468
Andy McFadden41d67d72014-04-25 16:58:34 -07004469 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004470 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004471 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004472
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004473 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4474 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004475 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4476 getHwComposer().isConnected(displayId)) {
4477 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004478 result.appendFormat("Display %d: "
4479 "app phase %" PRId64 " ns, "
4480 "sf phase %" PRId64 " ns, "
4481 "early app phase %" PRId64 " ns, "
4482 "early sf phase %" PRId64 " ns, "
4483 "early app gl phase %" PRId64 " ns, "
4484 "early sf gl phase %" PRId64 " ns, "
4485 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4486 displayId,
4487 vsyncPhaseOffsetNs,
4488 sfVsyncPhaseOffsetNs,
4489 appEarlyOffset,
4490 sfEarlyOffset,
4491 appEarlyGlOffset,
4492 sfEarlyOffset,
4493 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004494 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004495 result.append("\n");
4496
Dan Stozab90cf072015-03-05 11:05:59 -08004497 // Dump static screen stats
4498 result.append("\n");
4499 dumpStaticScreenStats(result);
4500 result.append("\n");
4501
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004502 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4503
Dan Stozae77c7662016-05-13 11:37:28 -07004504 dumpBufferingStats(result);
4505
Andy McFadden4803b742012-09-24 19:07:20 -07004506 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004507 * Dump the visible layer list
4508 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004509 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004510 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004511 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4512 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004513 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004514
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004515 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004516 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004517 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004518 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004519
4520 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004521 * Dump Display state
4522 */
4523
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004524 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004525 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004526 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004527 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004528 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004529 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004530 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004531
4532 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004533 * Dump SurfaceFlinger global state
4534 */
4535
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004536 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004537 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004538 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004539
Mathias Agopian888c8222012-08-04 21:10:38 -07004540 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004541 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004542
David Sodmanbc815282017-11-05 18:57:52 -08004543 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004544
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004545 if (display) {
4546 display->undefinedRegion.dump(result, "undefinedRegion");
4547 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4548 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004549 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004550 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4551 " last transaction time : %f us\n"
4552 " transaction-flags : %08x\n"
4553 " gpu_to_cpu_unsupported : %d\n",
4554 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4555 mTransactionFlags, !mGpuToCpuSupported);
4556
4557 if (display) {
4558 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4559 result.appendFormat(" refresh-rate : %f fps\n"
4560 " x-dpi : %f\n"
4561 " y-dpi : %f\n",
4562 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4563 activeConfig->getDpiY());
4564 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004565
Mathias Agopian74d211a2013-04-22 16:55:35 +02004566 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004567 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004568
Mathias Agopian74d211a2013-04-22 16:55:35 +02004569 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004570 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004571
4572 /*
4573 * VSYNC state
4574 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004575 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004576 result.append("\n");
4577
4578 /*
4579 * HWC layer minidump
4580 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004581 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004582 const int32_t displayId = display->getId();
4583 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004584 continue;
4585 }
4586
Dominik Laskowski7e045462018-05-30 13:02:02 -07004587 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004588 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004589 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004590 result.append("\n");
4591 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004592
4593 /*
4594 * Dump HWComposer state
4595 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004596 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004597 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004598 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004599 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004600 result.appendFormat(" h/w composer %s\n",
4601 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004602 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004603
4604 /*
4605 * Dump gralloc state
4606 */
4607 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4608 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004609
4610 /*
4611 * Dump VrFlinger state if in use.
4612 */
4613 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4614 result.append("VrFlinger state:\n");
4615 result.append(mVrFlinger->Dump().c_str());
4616 result.append("\n");
4617 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004618}
4619
Dominik Laskowski7e045462018-05-30 13:02:02 -07004620const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004621 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004622 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004623 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004624 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004625 }
4626 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004627
4628 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4629 static const Vector<sp<Layer>> empty;
4630 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004631}
4632
Keun young Park63f165f2012-08-31 10:53:36 -07004633bool SurfaceFlinger::startDdmConnection()
4634{
4635 void* libddmconnection_dso =
4636 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4637 if (!libddmconnection_dso) {
4638 return false;
4639 }
4640 void (*DdmConnection_start)(const char* name);
4641 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004642 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004643 if (!DdmConnection_start) {
4644 dlclose(libddmconnection_dso);
4645 return false;
4646 }
4647 (*DdmConnection_start)(getServiceName());
4648 return true;
4649}
4650
Chia-I Wu28f320b2018-05-03 11:02:56 -07004651void SurfaceFlinger::updateColorMatrixLocked() {
4652 mat4 colorMatrix;
4653 if (mGlobalSaturationFactor != 1.0f) {
4654 // Rec.709 luma coefficients
4655 float3 luminance{0.213f, 0.715f, 0.072f};
4656 luminance *= 1.0f - mGlobalSaturationFactor;
4657 mat4 saturationMatrix = mat4(
4658 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4659 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4660 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4661 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4662 );
4663 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4664 } else {
4665 colorMatrix = mClientColorMatrix * mDaltonizer();
4666 }
4667
4668 if (mCurrentState.colorMatrix != colorMatrix) {
4669 mCurrentState.colorMatrix = colorMatrix;
4670 mCurrentState.colorMatrixChanged = true;
4671 setTransactionFlags(eTransactionNeeded);
4672 }
4673}
4674
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004675status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004676 switch (code) {
4677 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004678 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004679 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004680 case CLEAR_ANIMATION_FRAME_STATS:
4681 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004682 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004683 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004684 case ENABLE_VSYNC_INJECTIONS:
4685 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004686 {
4687 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004688 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4689 IPCThreadState* ipc = IPCThreadState::self();
4690 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4691 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004692 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004693 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004694 break;
4695 }
Robert Carr1db73f62016-12-21 12:58:51 -08004696 /*
4697 * Calling setTransactionState is safe, because you need to have been
4698 * granted a reference to Client* and Handle* to do anything with it.
4699 *
4700 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4701 */
4702 case SET_TRANSACTION_STATE:
4703 case CREATE_SCOPED_CONNECTION:
4704 {
4705 return OK;
4706 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004707 case CAPTURE_SCREEN:
4708 {
4709 // codes that require permission check
4710 IPCThreadState* ipc = IPCThreadState::self();
4711 const int pid = ipc->getCallingPid();
4712 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004713 if ((uid != AID_GRAPHICS) &&
4714 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004715 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004716 return PERMISSION_DENIED;
4717 }
4718 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004719 }
chaviwa76b2712017-09-20 12:02:26 -07004720 case CAPTURE_LAYERS: {
4721 IPCThreadState* ipc = IPCThreadState::self();
4722 const int pid = ipc->getCallingPid();
4723 const int uid = ipc->getCallingUid();
4724 if ((uid != AID_GRAPHICS) &&
4725 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4726 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4727 return PERMISSION_DENIED;
4728 }
4729 break;
4730 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004731 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004732 return OK;
4733}
4734
4735status_t SurfaceFlinger::onTransact(
4736 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4737{
4738 status_t credentialCheck = CheckTransactCodeCredentials(code);
4739 if (credentialCheck != OK) {
4740 return credentialCheck;
4741 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004742
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004743 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4744 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004745 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004746 IPCThreadState* ipc = IPCThreadState::self();
4747 const int uid = ipc->getCallingUid();
4748 if (CC_UNLIKELY(uid != AID_SYSTEM
4749 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004750 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004751 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004752 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004753 return PERMISSION_DENIED;
4754 }
4755 int n;
4756 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004757 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004758 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004759 return NO_ERROR;
4760 case 1002: // SHOW_UPDATES
4761 n = data.readInt32();
4762 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004763 invalidateHwcGeometry();
4764 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004765 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004766 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004767 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004768 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004769 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004770 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004771 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004772 setTransactionFlags(
4773 eTransactionNeeded|
4774 eDisplayTransactionNeeded|
4775 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004776 return NO_ERROR;
4777 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004778 case 1006:{ // send empty update
4779 signalRefresh();
4780 return NO_ERROR;
4781 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004782 case 1008: // toggle use of hw composer
4783 n = data.readInt32();
4784 mDebugDisableHWC = n ? 1 : 0;
4785 invalidateHwcGeometry();
4786 repaintEverything();
4787 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004788 case 1009: // toggle use of transform hint
4789 n = data.readInt32();
4790 mDebugDisableTransformHint = n ? 1 : 0;
4791 invalidateHwcGeometry();
4792 repaintEverything();
4793 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004794 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004795 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004796 reply->writeInt32(0);
4797 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004798 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004799 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004800 return NO_ERROR;
4801 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004802 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004803 if (!display) {
4804 return NAME_NOT_FOUND;
4805 }
4806
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004807 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004808 return NO_ERROR;
4809 }
4810 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004811 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004812 // daltonize
4813 n = data.readInt32();
4814 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004815 case 1:
4816 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4817 break;
4818 case 2:
4819 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4820 break;
4821 case 3:
4822 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4823 break;
4824 default:
4825 mDaltonizer.setType(ColorBlindnessType::None);
4826 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004827 }
4828 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004829 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004830 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004831 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004832 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004833
4834 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004835 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004836 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004837 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004838 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004839 // apply a color matrix
4840 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004841 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004842 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004843 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004844 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004845 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004846 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004847 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004848 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004849 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004850 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004851
4852 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4853 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004854 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004855 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4856 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4857 }
4858
Chia-I Wu28f320b2018-05-03 11:02:56 -07004859 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004860 return NO_ERROR;
4861 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004862 // This is an experimental interface
4863 // Needs to be shifted to proper binder interface when we productize
4864 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004865 n = data.readInt32();
4866 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004867 return NO_ERROR;
4868 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004869 case 1017: {
4870 n = data.readInt32();
4871 mForceFullDamage = static_cast<bool>(n);
4872 return NO_ERROR;
4873 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004874 case 1018: { // Modify Choreographer's phase offset
4875 n = data.readInt32();
4876 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4877 return NO_ERROR;
4878 }
4879 case 1019: { // Modify SurfaceFlinger's phase offset
4880 n = data.readInt32();
4881 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4882 return NO_ERROR;
4883 }
Irvel468051e2016-06-13 16:44:44 -07004884 case 1020: { // Layer updates interceptor
4885 n = data.readInt32();
4886 if (n) {
4887 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004888 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004889 }
4890 else{
4891 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004892 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004893 }
4894 return NO_ERROR;
4895 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004896 case 1021: { // Disable HWC virtual displays
4897 n = data.readInt32();
4898 mUseHwcVirtualDisplays = !n;
4899 return NO_ERROR;
4900 }
Romain Guy0147a172017-06-01 13:53:56 -07004901 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004902 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004903 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004904
Chia-I Wu28f320b2018-05-03 11:02:56 -07004905 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004906 return NO_ERROR;
4907 }
Romain Guy54f154a2017-10-24 21:40:32 +01004908 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004909 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004910 invalidateHwcGeometry();
4911 repaintEverything();
4912 return NO_ERROR;
4913 }
4914 case 1024: { // Is wide color gamut rendering/color management supported?
4915 reply->writeBool(hasWideColorDisplay);
4916 return NO_ERROR;
4917 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004918 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004919 n = data.readInt32();
4920 if (n) {
4921 ALOGV("LayerTracing enabled");
4922 mTracing.enable();
4923 doTracing("tracing.enable");
4924 reply->writeInt32(NO_ERROR);
4925 } else {
4926 ALOGV("LayerTracing disabled");
4927 status_t err = mTracing.disable();
4928 reply->writeInt32(err);
4929 }
4930 return NO_ERROR;
4931 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004932 case 1026: { // Get layer tracing status
4933 reply->writeBool(mTracing.isEnabled());
4934 return NO_ERROR;
4935 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004936 // Is a DisplayColorSetting supported?
4937 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004938 const auto display = getDefaultDisplayDevice();
4939 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004940 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004941 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004942
4943 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4944 switch (setting) {
4945 case DisplayColorSetting::MANAGED:
4946 reply->writeBool(hasWideColorDisplay);
4947 break;
4948 case DisplayColorSetting::UNMANAGED:
4949 reply->writeBool(true);
4950 break;
4951 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004952 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004953 break;
4954 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004955 reply->writeBool(
4956 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004957 break;
4958 }
4959 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004960 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004961 // Is VrFlinger active?
4962 case 1028: {
4963 Mutex::Autolock _l(mStateLock);
4964 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4965 return NO_ERROR;
4966 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004967 }
4968 }
4969 return err;
4970}
4971
Steven Thomas6d8110b2017-08-31 18:24:21 -07004972void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004973 android_atomic_or(1, &mRepaintEverything);
4974 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004975}
4976
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004977// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4978class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004979public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004980 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4981 ~WindowDisconnector() {
4982 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004983 }
4984
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004985private:
4986 ANativeWindow* mWindow;
4987 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004988};
4989
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004990status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4991 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4992 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4993 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004994 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004995 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004996
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004997 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004998
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004999 const auto display = getDisplayDeviceLocked(displayToken);
5000 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005002 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07005003
5004 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005005 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005006 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005007}
5008
5009status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005010 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005011 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005012 ATRACE_CALL();
5013
5014 class LayerRenderArea : public RenderArea {
5015 public:
Robert Carr578038f2018-03-09 12:25:24 -08005016 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5017 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07005018 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005019 mLayer(layer),
5020 mCrop(crop),
5021 mFlinger(flinger),
5022 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005023 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005024 Rect getBounds() const override {
5025 const Layer::State& layerState(mLayer->getDrawingState());
5026 return Rect(layerState.active.w, layerState.active.h);
5027 }
5028 int getHeight() const override { return mLayer->getDrawingState().active.h; }
5029 int getWidth() const override { return mLayer->getDrawingState().active.w; }
5030 bool isSecure() const override { return false; }
5031 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005032 Rect getSourceCrop() const override {
5033 if (mCrop.isEmpty()) {
5034 return getBounds();
5035 } else {
5036 return mCrop;
5037 }
5038 }
Robert Carr578038f2018-03-09 12:25:24 -08005039 class ReparentForDrawing {
5040 public:
5041 const sp<Layer>& oldParent;
5042 const sp<Layer>& newParent;
5043
5044 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5045 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005046 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005047 }
Robert Carr15eae092018-03-23 13:43:53 -07005048 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005049 };
5050
5051 void render(std::function<void()> drawLayers) override {
5052 if (!mChildrenOnly) {
5053 mTransform = mLayer->getTransform().inverse();
5054 drawLayers();
5055 } else {
5056 Rect bounds = getBounds();
5057 screenshotParentLayer =
5058 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5059 bounds.getWidth(), bounds.getHeight(), 0);
5060
5061 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5062 drawLayers();
5063 }
5064 }
chaviwa76b2712017-09-20 12:02:26 -07005065
chaviwa76b2712017-09-20 12:02:26 -07005066 private:
chaviw7206d492017-11-10 16:16:12 -08005067 const sp<Layer> mLayer;
5068 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005069
5070 // In the "childrenOnly" case we reparent the children to a screenshot
5071 // layer which has no properties set and which does not draw.
5072 sp<ContainerLayer> screenshotParentLayer;
5073 Transform mTransform;
5074
5075 SurfaceFlinger* mFlinger;
5076 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005077 };
5078
5079 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5080 auto parent = layerHandle->owner.promote();
5081
chaviw7206d492017-11-10 16:16:12 -08005082 if (parent == nullptr || parent->isPendingRemoval()) {
5083 ALOGE("captureLayers called with a removed parent");
5084 return NAME_NOT_FOUND;
5085 }
5086
Robert Carr578038f2018-03-09 12:25:24 -08005087 const int uid = IPCThreadState::self()->getCallingUid();
5088 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5089 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5090 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5091 return PERMISSION_DENIED;
5092 }
5093
chaviw7206d492017-11-10 16:16:12 -08005094 Rect crop(sourceCrop);
5095 if (sourceCrop.width() <= 0) {
5096 crop.left = 0;
5097 crop.right = parent->getCurrentState().active.w;
5098 }
5099
5100 if (sourceCrop.height() <= 0) {
5101 crop.top = 0;
5102 crop.bottom = parent->getCurrentState().active.h;
5103 }
5104
5105 int32_t reqWidth = crop.width() * frameScale;
5106 int32_t reqHeight = crop.height() * frameScale;
5107
Robert Carr578038f2018-03-09 12:25:24 -08005108 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005109
Robert Carr578038f2018-03-09 12:25:24 -08005110 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005111 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5112 if (!layer->isVisible()) {
5113 return;
Robert Carr578038f2018-03-09 12:25:24 -08005114 } else if (childrenOnly && layer == parent.get()) {
5115 return;
chaviwa76b2712017-09-20 12:02:26 -07005116 }
5117 visitor(layer);
5118 });
5119 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005120 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005121}
5122
5123status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5124 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005125 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005126 bool useIdentityTransform) {
5127 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005128
Iris Chang7501ed62018-04-30 14:45:42 +08005129 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005130
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005131 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5132 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5133 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5134 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005135
5136 // This mutex protects syncFd and captureResult for communication of the return values from the
5137 // main thread back to this Binder thread
5138 std::mutex captureMutex;
5139 std::condition_variable captureCondition;
5140 std::unique_lock<std::mutex> captureLock(captureMutex);
5141 int syncFd = -1;
5142 std::optional<status_t> captureResult;
5143
Robert Carr03480e22018-01-04 16:02:06 -08005144 const int uid = IPCThreadState::self()->getCallingUid();
5145 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5146
Dominik Laskowski8c001672018-05-30 16:52:06 -07005147 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005148 // If there is a refresh pending, bug out early and tell the binder thread to try again
5149 // after the refresh.
5150 if (mRefreshPending) {
5151 ATRACE_NAME("Skipping screenshot for now");
5152 std::unique_lock<std::mutex> captureLock(captureMutex);
5153 captureResult = std::make_optional<status_t>(EAGAIN);
5154 captureCondition.notify_one();
5155 return;
5156 }
5157
5158 status_t result = NO_ERROR;
5159 int fd = -1;
5160 {
5161 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005162 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005163 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5164 useIdentityTransform, forSystem, &fd);
5165 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005166 }
5167
5168 {
5169 std::unique_lock<std::mutex> captureLock(captureMutex);
5170 syncFd = fd;
5171 captureResult = std::make_optional<status_t>(result);
5172 captureCondition.notify_one();
5173 }
5174 });
5175
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005176 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005177 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005178 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005179 while (*captureResult == EAGAIN) {
5180 captureResult.reset();
5181 result = postMessageAsync(message);
5182 if (result != NO_ERROR) {
5183 return result;
5184 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005185 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005186 }
5187 result = *captureResult;
5188 }
5189
5190 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005191 sync_wait(syncFd, -1);
5192 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005193 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005194
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005195 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005196}
5197
chaviwa76b2712017-09-20 12:02:26 -07005198void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5199 TraverseLayersFunction traverseLayers, bool yswap,
5200 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005201 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005202
Lloyd Pique144e1162017-12-20 16:44:52 -08005203 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005204
5205 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005206 const auto raWidth = renderArea.getWidth();
5207 const auto raHeight = renderArea.getHeight();
5208
5209 const auto reqWidth = renderArea.getReqWidth();
5210 const auto reqHeight = renderArea.getReqHeight();
5211 Rect sourceCrop = renderArea.getSourceCrop();
5212
Iris Chang7501ed62018-04-30 14:45:42 +08005213 bool filtering = false;
5214 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5215 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5216 static_cast<int32_t>(reqHeight) != raWidth;
5217 } else {
5218 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5219 static_cast<int32_t>(reqHeight) != raHeight;
5220 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005221
Dan Stozac1879002014-05-22 15:59:05 -07005222 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005223 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005224 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005225 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005226 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5227 Transform tr;
5228 uint32_t flags = 0x00;
5229 switch (mPrimaryDisplayOrientation) {
5230 case DisplayState::eOrientation90:
5231 flags = Transform::ROT_90;
5232 break;
5233 case DisplayState::eOrientation180:
5234 flags = Transform::ROT_180;
5235 break;
5236 case DisplayState::eOrientation270:
5237 flags = Transform::ROT_270;
5238 break;
5239 }
5240 tr.set(flags, raWidth, raHeight);
5241 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005242 }
5243
5244 // ensure that sourceCrop is inside screen
5245 if (sourceCrop.left < 0) {
5246 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5247 }
chaviwa76b2712017-09-20 12:02:26 -07005248 if (sourceCrop.right > raWidth) {
5249 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005250 }
5251 if (sourceCrop.top < 0) {
5252 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5253 }
chaviwa76b2712017-09-20 12:02:26 -07005254 if (sourceCrop.bottom > raHeight) {
5255 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005256 }
5257
Chia-I Wu36574d92018-05-16 10:54:36 -07005258 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5259 engine.setOutputDataSpace(Dataspace::SRGB);
5260 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005261
Mathias Agopian180f10d2013-04-10 22:55:41 -07005262 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005263 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005264
Iris Chang7501ed62018-04-30 14:45:42 +08005265 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5266 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5267 // convert hw orientation into flag presentation
5268 // here inverse transform needed
5269 uint8_t hw_rot_90 = 0x00;
5270 uint8_t hw_flip_hv = 0x00;
5271 switch (mPrimaryDisplayOrientation) {
5272 case DisplayState::eOrientation90:
5273 hw_rot_90 = Transform::ROT_90;
5274 hw_flip_hv = Transform::ROT_180;
5275 break;
5276 case DisplayState::eOrientation180:
5277 hw_flip_hv = Transform::ROT_180;
5278 break;
5279 case DisplayState::eOrientation270:
5280 hw_rot_90 = Transform::ROT_90;
5281 break;
5282 }
5283
5284 // transform flags operation
5285 // 1) flip H V if both have ROT_90 flag
5286 // 2) XOR these flags
5287 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5288 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5289 if (rotation_rot_90 & hw_rot_90) {
5290 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5291 }
5292 rotation = static_cast<Transform::orientation_flags>
5293 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5294 }
5295
Mathias Agopian180f10d2013-04-10 22:55:41 -07005296 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005297 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005298 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005299 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005300
chaviw50da5042018-04-09 13:49:37 -07005301 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005302 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005303 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005304
chaviwa76b2712017-09-20 12:02:26 -07005305 traverseLayers([&](Layer* layer) {
5306 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005307 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005308 if (filtering) layer->setFiltering(false);
5309 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005310}
5311
chaviwa76b2712017-09-20 12:02:26 -07005312status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5313 TraverseLayersFunction traverseLayers,
5314 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005315 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005316 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005317 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005318 ATRACE_CALL();
5319
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005320 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005321
5322 traverseLayers([&](Layer* layer) {
5323 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5324 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005325
Robert Carr03480e22018-01-04 16:02:06 -08005326 // We allow the system server to take screenshots of secure layers for
5327 // use in situations like the Screen-rotation animation and place
5328 // the impetus on WindowManager to not persist them.
5329 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005330 ALOGW("FB is protected: PERMISSION_DENIED");
5331 return PERMISSION_DENIED;
5332 }
5333
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005334 // this binds the given EGLImage as a framebuffer for the
5335 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005336 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005337 if (bufferBond.getStatus() != NO_ERROR) {
5338 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005339 return INVALID_OPERATION;
5340 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005341
Dan Stozaabcda352017-06-01 14:37:39 -07005342 // this will in fact render into our dequeued buffer
5343 // via an FBO, which means we didn't have to create
5344 // an EGLSurface and therefore we're not
5345 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005346 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005347
Dan Stozaabcda352017-06-01 14:37:39 -07005348 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005349 getRenderEngine().finish();
5350 *outSyncFd = -1;
5351
chaviwa76b2712017-09-20 12:02:26 -07005352 const auto reqWidth = renderArea.getReqWidth();
5353 const auto reqHeight = renderArea.getReqHeight();
5354
Dan Stozaabcda352017-06-01 14:37:39 -07005355 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5356 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005357 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005358 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005359 } else {
5360 base::unique_fd syncFd = getRenderEngine().flush();
5361 if (syncFd < 0) {
5362 getRenderEngine().finish();
5363 }
5364 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005365 }
5366
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005367 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005368}
5369
Mathias Agopiand5556842013-09-19 17:08:37 -07005370void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005371 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005372 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005373 for (size_t y = 0; y < h; y++) {
5374 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5375 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005376 if (p[x] != 0xFF000000) return;
5377 }
5378 }
chaviwa76b2712017-09-20 12:02:26 -07005379 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005380
Robert Carr2047fae2016-11-28 14:09:09 -08005381 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005382 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005383 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005384 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5385 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5386 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5387 static_cast<float>(state.color.a));
5388 i++;
5389 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005390 }
5391}
5392
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005393// ---------------------------------------------------------------------------
5394
Dan Stoza412903f2017-04-27 13:42:17 -07005395void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5396 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005397}
5398
Dan Stoza412903f2017-04-27 13:42:17 -07005399void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5400 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005401}
5402
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005403void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5404 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005405 const LayerVector::Visitor& visitor) {
5406 // We loop through the first level of layers without traversing,
5407 // as we need to interpret min/max layer Z in the top level Z space.
5408 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005409 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005410 continue;
5411 }
5412 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005413 // relative layers are traversed in Layer::traverseInZOrder
5414 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005415 continue;
5416 }
5417 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005418 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005419 return;
5420 }
chaviwa76b2712017-09-20 12:02:26 -07005421 if (!layer->isVisible()) {
5422 return;
5423 }
5424 visitor(layer);
5425 });
5426 }
5427}
5428
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005429}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005430
Mathias Agopian3f844832013-08-07 21:24:32 -07005431#if defined(__gl_h_)
5432#error "don't include gl/gl.h in this file"
5433#endif
5434
5435#if defined(__gl2_h_)
5436#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005437#endif