blob: 63e058ac17086cd2095352f9f24e458b05ad30ba [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 &&
3217 layer->isOpaque(state) && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003218 // never clear the very first layer since we're
3219 // guaranteed the FB is already cleared
3220 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003221 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003222 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003223 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003224 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003225 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003226 break;
3227 }
3228 default:
3229 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003230 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003231 } else {
3232 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003233 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003234 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003235 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003236
Chia-I Wud49d6692018-06-27 07:17:41 +08003237 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003238 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003239 }
3240
Mathias Agopianf45c5102012-10-24 16:29:17 -07003241 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003242 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003243 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003244}
3245
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003246void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3247 const Region& region) const {
3248 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003249 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003250 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003251}
3252
Dan Stoza7d89d062015-04-30 13:29:25 -07003253status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003254 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003255 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003256 const sp<Layer>& lbc,
3257 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003258{
Dan Stoza7d89d062015-04-30 13:29:25 -07003259 // add this layer to the current state list
3260 {
3261 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003262 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003263 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3264 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003265 return NO_MEMORY;
3266 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003267 if (parent == nullptr) {
3268 mCurrentState.layersSortedByZ.add(lbc);
3269 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003270 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003271 ALOGE("addClientLayer called with a removed parent");
3272 return NAME_NOT_FOUND;
3273 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003274 parent->addChild(lbc);
3275 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003276
Yiwei Zhang243b3782018-05-15 17:40:04 -07003277 if (gbc != nullptr) {
3278 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3279 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3280 mMaxGraphicBufferProducerListSize,
3281 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3282 mGraphicBufferProducerList.size(),
3283 mMaxGraphicBufferProducerListSize, mNumLayers);
3284 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003285 mLayersAdded = true;
3286 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003287 }
3288
Mathias Agopian96f08192010-06-02 23:28:45 -07003289 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003290 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003291
Dan Stoza7d89d062015-04-30 13:29:25 -07003292 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003293}
3294
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003295status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003296 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003297 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3298}
Robert Carr7f9b8992017-03-10 11:08:39 -08003299
chaviwca27f252018-02-06 16:46:39 -08003300status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3301 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003302 if (layer->isPendingRemoval()) {
3303 return NO_ERROR;
3304 }
3305
Robert Carr1f0a16a2016-10-24 16:27:39 -07003306 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003307 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003308 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003309 if (topLevelOnly) {
3310 return NO_ERROR;
3311 }
3312
Chia-I Wu98f1c102017-05-30 14:54:08 -07003313 sp<Layer> ancestor = p;
3314 while (ancestor->getParent() != nullptr) {
3315 ancestor = ancestor->getParent();
3316 }
3317 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3318 ALOGE("removeLayer called with a layer whose parent has been removed");
3319 return NAME_NOT_FOUND;
3320 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003321
3322 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003323 } else {
3324 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003325 }
3326
Robert Carr136e2f62017-02-08 17:54:29 -08003327 // As a matter of normal operation, the LayerCleaner will produce a second
3328 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3329 // so we will succeed in promoting it, but it's already been removed
3330 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3331 // otherwise something has gone wrong and we are leaking the layer.
3332 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003333 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3334 layer->getName().string(),
3335 (p != nullptr) ? p->getName().string() : "no-parent");
3336 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003337 } else if (index < 0) {
3338 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003339 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003340
Chia-I Wuc6657022017-08-15 11:18:17 -07003341 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003342 mLayersPendingRemoval.add(layer);
3343 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003344 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003345 setTransactionFlags(eTransactionNeeded);
3346 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003347}
3348
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003349uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003350 return android_atomic_release_load(&mTransactionFlags);
3351}
3352
Mathias Agopian3f844832013-08-07 21:24:32 -07003353uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003354 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3355}
3356
Mathias Agopian3f844832013-08-07 21:24:32 -07003357uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003358 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3359}
3360
3361uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3362 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003363 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003364 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003365 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003366 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003367 }
3368 return old;
3369}
3370
chaviwca27f252018-02-06 16:46:39 -08003371bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3372 for (const ComposerState& state : states) {
3373 // Here we need to check that the interface we're given is indeed
3374 // one of our own. A malicious client could give us a nullptr
3375 // IInterface, or one of its own or even one of our own but a
3376 // different type. All these situations would cause us to crash.
3377 if (state.client == nullptr) {
3378 return true;
3379 }
3380
3381 sp<IBinder> binder = IInterface::asBinder(state.client);
3382 if (binder == nullptr) {
3383 return true;
3384 }
3385
3386 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3387 return true;
3388 }
3389 }
3390 return false;
3391}
3392
Mathias Agopian8b33f032012-07-24 20:43:54 -07003393void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003394 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003395 const Vector<DisplayState>& displays,
3396 uint32_t flags)
3397{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003398 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003399 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003400 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003401
chaviwca27f252018-02-06 16:46:39 -08003402 if (containsAnyInvalidClientState(states)) {
3403 return;
3404 }
3405
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003406 if (flags & eAnimation) {
3407 // For window updates that are part of an animation we must wait for
3408 // previous animation "frames" to be handled.
3409 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003410 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003411 if (CC_UNLIKELY(err != NO_ERROR)) {
3412 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003413 // caller after a few seconds.
3414 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3415 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003416 mAnimTransactionPending = false;
3417 break;
3418 }
3419 }
3420 }
3421
chaviwca27f252018-02-06 16:46:39 -08003422 for (const DisplayState& display : displays) {
3423 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003424 }
3425
chaviwca27f252018-02-06 16:46:39 -08003426 for (const ComposerState& state : states) {
3427 transactionFlags |= setClientStateLocked(state);
3428 }
3429
3430 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3431 // as destroyed should only occur after setting all other states. This is to allow for a
3432 // child re-parent to happen before marking its original parent as destroyed (which would
3433 // then mark the child as destroyed).
3434 for (const ComposerState& state : states) {
3435 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003436 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003437
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003438 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3439 // anyway. This can be used as a flush mechanism for previous async transactions.
3440 // Empty animation transaction can be used to simulate back-pressure, so also force a
3441 // transaction for empty animation transactions.
3442 if (transactionFlags == 0 &&
3443 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003444 transactionFlags = eTransactionNeeded;
3445 }
3446
Mathias Agopian386aa982011-11-07 21:58:03 -08003447 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003448 if (mInterceptor->isEnabled()) {
3449 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003450 }
Irvel468051e2016-06-13 16:44:44 -07003451
Mathias Agopian386aa982011-11-07 21:58:03 -08003452 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003453 const auto start = (flags & eEarlyWakeup)
3454 ? VSyncModulator::TransactionStart::EARLY
3455 : VSyncModulator::TransactionStart::NORMAL;
3456 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003457
3458 // if this is a synchronous transaction, wait for it to take effect
3459 // before returning.
3460 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003461 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003462 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003463 if (flags & eAnimation) {
3464 mAnimTransactionPending = true;
3465 }
3466 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003467 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3468 if (CC_UNLIKELY(err != NO_ERROR)) {
3469 // just in case something goes wrong in SF, return to the
3470 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003471 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3472 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003473 break;
3474 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003475 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003476 }
3477}
3478
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003479uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3480 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3481 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003482
Mathias Agopiane57f2922012-08-09 16:29:12 -07003483 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003484 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3485
3486 const uint32_t what = s.what;
3487 if (what & DisplayState::eSurfaceChanged) {
3488 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3489 state.surface = s.surface;
3490 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003491 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003492 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003493 if (what & DisplayState::eLayerStackChanged) {
3494 if (state.layerStack != s.layerStack) {
3495 state.layerStack = s.layerStack;
3496 flags |= eDisplayTransactionNeeded;
3497 }
3498 }
3499 if (what & DisplayState::eDisplayProjectionChanged) {
3500 if (state.orientation != s.orientation) {
3501 state.orientation = s.orientation;
3502 flags |= eDisplayTransactionNeeded;
3503 }
3504 if (state.frame != s.frame) {
3505 state.frame = s.frame;
3506 flags |= eDisplayTransactionNeeded;
3507 }
3508 if (state.viewport != s.viewport) {
3509 state.viewport = s.viewport;
3510 flags |= eDisplayTransactionNeeded;
3511 }
3512 }
3513 if (what & DisplayState::eDisplaySizeChanged) {
3514 if (state.width != s.width) {
3515 state.width = s.width;
3516 flags |= eDisplayTransactionNeeded;
3517 }
3518 if (state.height != s.height) {
3519 state.height = s.height;
3520 flags |= eDisplayTransactionNeeded;
3521 }
3522 }
3523
Mathias Agopiane57f2922012-08-09 16:29:12 -07003524 return flags;
3525}
3526
Robert Carrd4ae7f32018-06-07 16:10:57 -07003527bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3528 IPCThreadState* ipc = IPCThreadState::self();
3529 const int pid = ipc->getCallingPid();
3530 const int uid = ipc->getCallingUid();
3531
3532 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3533 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3534 return false;
3535 }
3536 return true;
3537}
3538
chaviwca27f252018-02-06 16:46:39 -08003539uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3540 const layer_state_t& s = composerState.state;
3541 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3542
Mathias Agopian13127d82013-03-05 17:47:11 -08003543 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003544 if (layer == nullptr) {
3545 return 0;
3546 }
3547
3548 if (layer->isPendingRemoval()) {
3549 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3550 return 0;
3551 }
3552
3553 uint32_t flags = 0;
3554
3555 const uint32_t what = s.what;
3556 bool geometryAppliesWithResize =
3557 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003558
3559 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3560 // pending state will also be deferred.
3561 if (what & layer_state_t::eDeferTransaction) {
3562 layer->pushPendingState();
3563 }
3564
chaviw8b3871a2017-11-01 17:41:01 -07003565 if (what & layer_state_t::ePositionChanged) {
3566 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3567 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003568 }
chaviw8b3871a2017-11-01 17:41:01 -07003569 }
3570 if (what & layer_state_t::eLayerChanged) {
3571 // NOTE: index needs to be calculated before we update the state
3572 const auto& p = layer->getParent();
3573 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003574 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003575 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003576 mCurrentState.layersSortedByZ.removeAt(idx);
3577 mCurrentState.layersSortedByZ.add(layer);
3578 // we need traversal (state changed)
3579 // AND transaction (list changed)
3580 flags |= eTransactionNeeded|eTraversalNeeded;
3581 }
chaviw8b3871a2017-11-01 17:41:01 -07003582 } else {
3583 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003584 flags |= eTransactionNeeded|eTraversalNeeded;
3585 }
3586 }
chaviw8b3871a2017-11-01 17:41:01 -07003587 }
3588 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003589 // NOTE: index needs to be calculated before we update the state
3590 const auto& p = layer->getParent();
3591 if (p == nullptr) {
3592 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3593 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3594 mCurrentState.layersSortedByZ.removeAt(idx);
3595 mCurrentState.layersSortedByZ.add(layer);
3596 // we need traversal (state changed)
3597 // AND transaction (list changed)
3598 flags |= eTransactionNeeded|eTraversalNeeded;
3599 }
3600 } else {
3601 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3602 flags |= eTransactionNeeded|eTraversalNeeded;
3603 }
chaviw8b3871a2017-11-01 17:41:01 -07003604 }
3605 }
3606 if (what & layer_state_t::eSizeChanged) {
3607 if (layer->setSize(s.w, s.h)) {
3608 flags |= eTraversalNeeded;
3609 }
3610 }
3611 if (what & layer_state_t::eAlphaChanged) {
3612 if (layer->setAlpha(s.alpha))
3613 flags |= eTraversalNeeded;
3614 }
3615 if (what & layer_state_t::eColorChanged) {
3616 if (layer->setColor(s.color))
3617 flags |= eTraversalNeeded;
3618 }
3619 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003620 // TODO: b/109894387
3621 //
3622 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3623 // rotation. To see the problem observe that if we have a square parent, and a child
3624 // of the same size, then we rotate the child 45 degrees around it's center, the child
3625 // must now be cropped to a non rectangular 8 sided region.
3626 //
3627 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3628 // private API, and the WindowManager only uses rotation in one case, which is on a top
3629 // level layer in which cropping is not an issue.
3630 //
3631 // However given that abuse of rotation matrices could lead to surfaces extending outside
3632 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3633 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3634 // transformations.
3635 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003636 flags |= eTraversalNeeded;
3637 }
3638 if (what & layer_state_t::eTransparentRegionChanged) {
3639 if (layer->setTransparentRegionHint(s.transparentRegion))
3640 flags |= eTraversalNeeded;
3641 }
3642 if (what & layer_state_t::eFlagsChanged) {
3643 if (layer->setFlags(s.flags, s.mask))
3644 flags |= eTraversalNeeded;
3645 }
3646 if (what & layer_state_t::eCropChanged) {
3647 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3648 flags |= eTraversalNeeded;
3649 }
3650 if (what & layer_state_t::eFinalCropChanged) {
3651 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3652 flags |= eTraversalNeeded;
3653 }
3654 if (what & layer_state_t::eLayerStackChanged) {
3655 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3656 // We only allow setting layer stacks for top level layers,
3657 // everything else inherits layer stack from its parent.
3658 if (layer->hasParent()) {
3659 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3660 layer->getName().string());
3661 } else if (idx < 0) {
3662 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3663 "that also does not appear in the top level layer list. Something"
3664 " has gone wrong.", layer->getName().string());
3665 } else if (layer->setLayerStack(s.layerStack)) {
3666 mCurrentState.layersSortedByZ.removeAt(idx);
3667 mCurrentState.layersSortedByZ.add(layer);
3668 // we need traversal (state changed)
3669 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003670 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003671 }
3672 }
3673 if (what & layer_state_t::eDeferTransaction) {
3674 if (s.barrierHandle != nullptr) {
3675 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3676 } else if (s.barrierGbp != nullptr) {
3677 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3678 if (authenticateSurfaceTextureLocked(gbp)) {
3679 const auto& otherLayer =
3680 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3681 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3682 } else {
3683 ALOGE("Attempt to defer transaction to to an"
3684 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003685 }
3686 }
chaviw8b3871a2017-11-01 17:41:01 -07003687 // We don't trigger a traversal here because if no other state is
3688 // changed, we don't want this to cause any more work
3689 }
3690 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003691 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003692 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003693 if (!hadParent) {
3694 mCurrentState.layersSortedByZ.remove(layer);
3695 }
chaviw8b3871a2017-11-01 17:41:01 -07003696 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003697 }
chaviw8b3871a2017-11-01 17:41:01 -07003698 }
3699 if (what & layer_state_t::eReparentChildren) {
3700 if (layer->reparentChildren(s.reparentHandle)) {
3701 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003702 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003703 }
chaviw8b3871a2017-11-01 17:41:01 -07003704 if (what & layer_state_t::eDetachChildren) {
3705 layer->detachChildren();
3706 }
3707 if (what & layer_state_t::eOverrideScalingModeChanged) {
3708 layer->setOverrideScalingMode(s.overrideScalingMode);
3709 // We don't trigger a traversal here because if no other state is
3710 // changed, we don't want this to cause any more work
3711 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003712 return flags;
3713}
3714
chaviwca27f252018-02-06 16:46:39 -08003715void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3716 const layer_state_t& state = composerState.state;
3717 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3718
3719 sp<Layer> layer(client->getLayerUser(state.surface));
3720 if (layer == nullptr) {
3721 return;
3722 }
3723
3724 if (layer->isPendingRemoval()) {
3725 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3726 return;
3727 }
3728
3729 if (state.what & layer_state_t::eDestroySurface) {
3730 removeLayerLocked(mStateLock, layer);
3731 }
3732}
3733
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003734status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003735 const String8& name,
3736 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003737 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003738 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003739 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003740{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003741 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003742 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003743 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003744 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003745 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003746
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003747 status_t result = NO_ERROR;
3748
3749 sp<Layer> layer;
3750
Cody Northropbc755282017-03-31 12:00:08 -06003751 String8 uniqueName = getUniqueLayerName(name);
3752
Mathias Agopian3165cc22012-08-08 19:42:09 -07003753 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3754 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003755 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003756 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003757 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003758
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003759 break;
chaviw13fdc492017-06-27 12:40:18 -07003760 case ISurfaceComposerClient::eFXSurfaceColor:
3761 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003762 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003763 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003764 break;
3765 default:
3766 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003767 break;
3768 }
3769
Dan Stoza7d89d062015-04-30 13:29:25 -07003770 if (result != NO_ERROR) {
3771 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003772 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003773
Chia-I Wuab0c3192017-08-01 11:29:00 -07003774 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3775 // TODO b/64227542
3776 if (windowType == 441731) {
3777 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3778 layer->setPrimaryDisplayOnly();
3779 }
3780
Albert Chaulk479c60c2017-01-27 14:21:34 -05003781 layer->setInfo(windowType, ownerUid);
3782
Robert Carr1f0a16a2016-10-24 16:27:39 -07003783 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003784 if (result != NO_ERROR) {
3785 return result;
3786 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003787 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003788
3789 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003790 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003791}
3792
Cody Northropbc755282017-03-31 12:00:08 -06003793String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3794{
3795 bool matchFound = true;
3796 uint32_t dupeCounter = 0;
3797
3798 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3799 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3800
Dan Stoza436ccf32018-06-21 12:10:12 -07003801 // Grab the state lock since we're accessing mCurrentState
3802 Mutex::Autolock lock(mStateLock);
3803
Cody Northropbc755282017-03-31 12:00:08 -06003804 // Loop over layers until we're sure there is no matching name
3805 while (matchFound) {
3806 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003807 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003808 if (layer->getName() == uniqueName) {
3809 matchFound = true;
3810 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3811 }
3812 });
3813 }
3814
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003815 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3816 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003817
3818 return uniqueName;
3819}
3820
David Sodman0c69cad2017-08-21 12:12:51 -07003821status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003822 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3823 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003824{
3825 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003826 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003827 case PIXEL_FORMAT_TRANSPARENT:
3828 case PIXEL_FORMAT_TRANSLUCENT:
3829 format = PIXEL_FORMAT_RGBA_8888;
3830 break;
3831 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003832 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003833 break;
3834 }
3835
David Sodman0c69cad2017-08-21 12:12:51 -07003836 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3837 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003838 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003839 *handle = layer->getHandle();
3840 *gbp = layer->getProducer();
3841 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003842 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003843
David Sodman0c69cad2017-08-21 12:12:51 -07003844 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003845 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003846}
3847
chaviw13fdc492017-06-27 12:40:18 -07003848status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003849 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003850 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003851{
chaviw13fdc492017-06-27 12:40:18 -07003852 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003853 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003854 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003855}
3856
Mathias Agopianac9fa422013-02-11 16:40:36 -08003857status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003858{
Robert Carr9524cb32017-02-13 11:32:32 -08003859 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003860 status_t err = NO_ERROR;
3861 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003862 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003863 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003864 err = removeLayer(l);
3865 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3866 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003867 }
3868 return err;
3869}
3870
Mathias Agopian13127d82013-03-05 17:47:11 -08003871status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003872{
Mathias Agopian67106042013-03-14 19:18:13 -07003873 // called by ~LayerCleaner() when all references to the IBinder (handle)
3874 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003875 sp<Layer> l = layer.promote();
3876 if (l == nullptr) {
3877 // The layer has already been removed, carry on
3878 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003879 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003880 // If we have a parent, then we can continue to live as long as it does.
3881 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003882}
3883
Mathias Agopianb60314a2012-04-10 22:09:54 -07003884// ---------------------------------------------------------------------------
3885
Andy McFadden13a082e2012-08-24 10:16:42 -07003886void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003887 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3888 if (!displayToken) return;
3889
Jesse Hall01e29052013-02-19 16:13:35 -08003890 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003891 Vector<ComposerState> state;
3892 Vector<DisplayState> displays;
3893 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003894 d.what = DisplayState::eDisplayProjectionChanged |
3895 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003896 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003897 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003898 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003899 d.frame.makeInvalid();
3900 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003901 d.width = 0;
3902 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003903 displays.add(d);
3904 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003905
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003906 const auto display = getDisplayDevice(displayToken);
3907 if (!display) return;
3908
3909 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3910
3911 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003912 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003913 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003914
Brian Andersond0010582017-03-07 13:20:31 -08003915 // Use phase of 0 since phase is not known.
3916 // Use latency of 0, which will snap to the ideal latency.
3917 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003918}
3919
3920void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003921 // Async since we may be called from the main thread.
3922 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003923}
3924
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003925void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3926 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003927 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003928 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003929
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003930 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003931 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003932 return;
3933 }
3934
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003935 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003936 ALOGW("Trying to set power mode for virtual display");
3937 return;
3938 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003939
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003940 display->setPowerMode(mode);
3941
Lloyd Pique4dccc412018-01-22 17:21:36 -08003942 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003943 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003944 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003945 if (idx < 0) {
3946 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3947 return;
3948 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003949 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003950 }
3951
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003952 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003953 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003954 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003955 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003956 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003957 // FIXME: eventthread only knows about the main display right now
3958 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003959 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003960 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003961
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003962 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003963 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003964 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003965
3966 struct sched_param param = {0};
3967 param.sched_priority = 1;
3968 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3969 ALOGW("Couldn't set SCHED_FIFO on display on");
3970 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003971 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003972 // Turn off the display
3973 struct sched_param param = {0};
3974 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3975 ALOGW("Couldn't set SCHED_OTHER on display off");
3976 }
3977
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003978 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003979 disableHardwareVsync(true); // also cancels any in-progress resync
3980
Mathias Agopiancde87a32012-09-13 14:09:01 -07003981 // FIXME: eventthread only knows about the main display right now
3982 mEventThread->onScreenReleased();
3983 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003984
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003985 getHwComposer().setPowerMode(type, mode);
3986 mVisibleRegionsDirty = true;
3987 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003988 } else if (mode == HWC_POWER_MODE_DOZE ||
3989 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003990 // Update display while dozing
3991 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003992 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003993 // FIXME: eventthread only knows about the main display right now
3994 mEventThread->onScreenAcquired();
3995 resyncToHardwareVsync(true);
3996 }
3997 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3998 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003999 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004000 disableHardwareVsync(true); // also cancels any in-progress resync
4001 // FIXME: eventthread only knows about the main display right now
4002 mEventThread->onScreenReleased();
4003 }
4004 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004005 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004006 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004007 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004008 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004009
4010 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004011}
4012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004013void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004014 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004015 const auto display = getDisplayDevice(displayToken);
4016 if (!display) {
4017 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4018 displayToken.get());
4019 } else if (display->isVirtual()) {
4020 ALOGW("Attempt to set power mode %d for virtual display", mode);
4021 } else {
4022 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004023 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004024 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004025}
4026
4027// ---------------------------------------------------------------------------
4028
Lloyd Pique755e3192018-01-31 16:46:15 -08004029status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4030 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004031 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004032
Mathias Agopianbd115332013-04-18 16:41:04 -07004033 IPCThreadState* ipc = IPCThreadState::self();
4034 const int pid = ipc->getCallingPid();
4035 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004036
Mathias Agopianbd115332013-04-18 16:41:04 -07004037 if ((uid != AID_SHELL) &&
4038 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004039 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004040 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004041 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004042 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004043 // (this would indicate SF is stuck, but we want to be able to
4044 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004045 status_t err = mStateLock.timedLock(s2ns(1));
4046 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004047 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004048 result.appendFormat(
4049 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4050 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004051 }
4052
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004053 bool dumpAll = true;
4054 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004055 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004056
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004057 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004058 if ((index < numArgs) &&
4059 (args[index] == String16("--list"))) {
4060 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004061 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004062 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004063 }
4064
4065 if ((index < numArgs) &&
4066 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004067 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004068 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004069 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004070 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004071
4072 if ((index < numArgs) &&
4073 (args[index] == String16("--latency-clear"))) {
4074 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004075 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004076 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004077 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004078
4079 if ((index < numArgs) &&
4080 (args[index] == String16("--dispsync"))) {
4081 index++;
4082 mPrimaryDispSync.dump(result);
4083 dumpAll = false;
4084 }
Dan Stozab90cf072015-03-05 11:05:59 -08004085
4086 if ((index < numArgs) &&
4087 (args[index] == String16("--static-screen"))) {
4088 index++;
4089 dumpStaticScreenStats(result);
4090 dumpAll = false;
4091 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004092
4093 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004094 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004095 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004096 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004097 dumpAll = false;
4098 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004099
4100 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4101 index++;
4102 dumpWideColorInfo(result);
4103 dumpAll = false;
4104 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004105
4106 if ((index < numArgs) &&
4107 (args[index] == String16("--enable-layer-stats"))) {
4108 index++;
4109 mLayerStats.enable();
4110 dumpAll = false;
4111 }
4112
4113 if ((index < numArgs) &&
4114 (args[index] == String16("--disable-layer-stats"))) {
4115 index++;
4116 mLayerStats.disable();
4117 dumpAll = false;
4118 }
4119
4120 if ((index < numArgs) &&
4121 (args[index] == String16("--clear-layer-stats"))) {
4122 index++;
4123 mLayerStats.clear();
4124 dumpAll = false;
4125 }
4126
4127 if ((index < numArgs) &&
4128 (args[index] == String16("--dump-layer-stats"))) {
4129 index++;
4130 mLayerStats.dump(result);
4131 dumpAll = false;
4132 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004133
4134 if ((index < numArgs) &&
4135 (args[index] == String16("--display-identification"))) {
4136 index++;
4137 dumpDisplayIdentificationData(result);
4138 dumpAll = false;
4139 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004140
4141 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4142 index++;
4143 mTimeStats.parseArgs(asProto, args, index, result);
4144 dumpAll = false;
4145 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004146 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004147
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004148 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004149 if (asProto) {
4150 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4151 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4152 } else {
4153 dumpAllLocked(args, index, result);
4154 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004155 }
4156
Mathias Agopian9795c422009-08-26 16:36:26 -07004157 if (locked) {
4158 mStateLock.unlock();
4159 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004160 }
4161 write(fd, result.string(), result.size());
4162 return NO_ERROR;
4163}
4164
Dan Stozac7014012014-02-14 15:03:43 -08004165void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4166 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004167{
Robert Carr2047fae2016-11-28 14:09:09 -08004168 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004169 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004170 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004171}
4172
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004173void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004174 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004175{
4176 String8 name;
4177 if (index < args.size()) {
4178 name = String8(args[index]);
4179 index++;
4180 }
4181
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004182 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4183 getHwComposer().isConnected(displayId)) {
4184 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4185 const nsecs_t period = activeConfig->getVsyncPeriod();
4186 result.appendFormat("%" PRId64 "\n", period);
4187 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004188
4189 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004190 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004191 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004192 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004193 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004194 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004195 }
Robert Carr2047fae2016-11-28 14:09:09 -08004196 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004197 }
4198}
4199
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004200void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004201 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004202{
4203 String8 name;
4204 if (index < args.size()) {
4205 name = String8(args[index]);
4206 index++;
4207 }
4208
Robert Carr2047fae2016-11-28 14:09:09 -08004209 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004210 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004211 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004212 }
Robert Carr2047fae2016-11-28 14:09:09 -08004213 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004214
Svetoslavd85084b2014-03-20 10:28:31 -07004215 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004216}
4217
Jamie Gennis6547ff42013-07-16 20:12:42 -07004218// This should only be called from the main thread. Otherwise it would need
4219// the lock and should use mCurrentState rather than mDrawingState.
4220void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004221 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004222 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004223 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004224
4225 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4226}
4227
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004228void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004229{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004230 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004231
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004232 if (isLayerTripleBufferingDisabled())
4233 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004234
4235 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004236 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004237 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004238 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004239 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4240 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004241 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004242}
4243
Dan Stozab90cf072015-03-05 11:05:59 -08004244void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4245{
4246 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004247 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4248 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004249 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004250 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004251 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4252 b + 1, bucketTimeSec, percent);
4253 }
David Sodman4a36e932017-11-07 14:29:47 -08004254 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004255 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004256 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004257 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004258 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004259}
4260
Dan Stozae77c7662016-05-13 11:37:28 -07004261void SurfaceFlinger::recordBufferingStats(const char* layerName,
4262 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004263 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4264 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004265 for (const auto& segment : history) {
4266 if (!segment.usedThirdBuffer) {
4267 stats.twoBufferTime += segment.totalTime;
4268 }
4269 if (segment.occupancyAverage < 1.0f) {
4270 stats.doubleBufferedTime += segment.totalTime;
4271 } else if (segment.occupancyAverage < 2.0f) {
4272 stats.tripleBufferedTime += segment.totalTime;
4273 }
4274 ++stats.numSegments;
4275 stats.totalTime += segment.totalTime;
4276 }
4277}
4278
Brian Andersond6927fb2016-07-23 23:37:30 -07004279void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4280 result.appendFormat("Layer frame timestamps:\n");
4281
4282 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4283 const size_t count = currentLayers.size();
4284 for (size_t i=0 ; i<count ; i++) {
4285 currentLayers[i]->dumpFrameEvents(result);
4286 }
4287}
4288
Dan Stozae77c7662016-05-13 11:37:28 -07004289void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4290 result.append("Buffering stats:\n");
4291 result.append(" [Layer name] <Active time> <Two buffer> "
4292 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004293 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004294 typedef std::tuple<std::string, float, float, float> BufferTuple;
4295 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004296 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004297 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004298 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004299 if (stats.numSegments == 0) {
4300 continue;
4301 }
4302 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4303 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4304 stats.totalTime;
4305 float doubleBufferRatio = static_cast<float>(
4306 stats.doubleBufferedTime) / stats.totalTime;
4307 float tripleBufferRatio = static_cast<float>(
4308 stats.tripleBufferedTime) / stats.totalTime;
4309 sorted.insert({activeTime, {name, twoBufferRatio,
4310 doubleBufferRatio, tripleBufferRatio}});
4311 }
4312 for (const auto& sortedPair : sorted) {
4313 float activeTime = sortedPair.first;
4314 const BufferTuple& values = sortedPair.second;
4315 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4316 std::get<0>(values).c_str(), activeTime,
4317 std::get<1>(values), std::get<2>(values),
4318 std::get<3>(values));
4319 }
4320 result.append("\n");
4321}
4322
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004323void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004324 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004325 const int32_t displayId = display->getId();
4326 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4327 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004328 continue;
4329 }
4330
Dominik Laskowski7e045462018-05-30 13:02:02 -07004331 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004332 uint8_t port;
4333 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004334 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004335 result.append("no identification data\n");
4336 continue;
4337 }
4338
4339 if (!isEdid(data)) {
4340 result.append("unknown identification data: ");
4341 for (uint8_t byte : data) {
4342 result.appendFormat("%x ", byte);
4343 }
4344 result.append("\n");
4345 continue;
4346 }
4347
4348 const auto edid = parseEdid(data);
4349 if (!edid) {
4350 result.append("invalid EDID: ");
4351 for (uint8_t byte : data) {
4352 result.appendFormat("%x ", byte);
4353 }
4354 result.append("\n");
4355 continue;
4356 }
4357
4358 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4359 result.append(edid->displayName.data(), edid->displayName.length());
4360 result.append("\"\n");
4361 }
4362 result.append("\n");
4363}
4364
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004365void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4366 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004367 result.appendFormat("DisplayColorSetting: %s\n",
4368 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004369
4370 // TODO: print out if wide-color mode is active or not
4371
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004372 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004373 const int32_t displayId = display->getId();
4374 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004375 continue;
4376 }
4377
Dominik Laskowski7e045462018-05-30 13:02:02 -07004378 result.appendFormat("Display %d color modes:\n", displayId);
4379 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004380 for (auto&& mode : modes) {
4381 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4382 }
4383
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004384 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004385 result.appendFormat(" Current color mode: %s (%d)\n",
4386 decodeColorMode(currentMode).c_str(), currentMode);
4387 }
4388 result.append("\n");
4389}
4390
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004391LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004392 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004393 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4394 const State& state = useDrawing ? mDrawingState : mCurrentState;
4395 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004396 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004397 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004398 });
4399
4400 return layersProto;
4401}
4402
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004403LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004404 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004405
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004406 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004407 resolution->set_w(display.getWidth());
4408 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004409
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004410 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4411 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4412 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004413
Dominik Laskowski7e045462018-05-30 13:02:02 -07004414 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004415 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004416 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004417 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004418 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004419 }
4420 });
4421
4422 return layersProto;
4423}
4424
Mathias Agopian74d211a2013-04-22 16:55:35 +02004425void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4426 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004427{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004428 bool colorize = false;
4429 if (index < args.size()
4430 && (args[index] == String16("--color"))) {
4431 colorize = true;
4432 index++;
4433 }
4434
4435 Colorizer colorizer(colorize);
4436
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004437 // figure out if we're stuck somewhere
4438 const nsecs_t now = systemTime();
4439 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4440 const nsecs_t inTransaction(mDebugInTransaction);
4441 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4442 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4443
4444 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004445 * Dump library configuration.
4446 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004447
4448 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004449 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004450 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004451 appendSfConfigString(result);
4452 appendUiConfigString(result);
4453 appendGuiConfigString(result);
4454 result.append("\n");
4455
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004456 result.append("\nDisplay identification data:\n");
4457 dumpDisplayIdentificationData(result);
4458
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004459 result.append("\nWide-Color information:\n");
4460 dumpWideColorInfo(result);
4461
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004462 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004463 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004464 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004465 result.append(SyncFeatures::getInstance().toString());
4466 result.append("\n");
4467
Andy McFadden41d67d72014-04-25 16:58:34 -07004468 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004469 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004470 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004471
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004472 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4473 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004474 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4475 getHwComposer().isConnected(displayId)) {
4476 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004477 result.appendFormat("Display %d: "
4478 "app phase %" PRId64 " ns, "
4479 "sf phase %" PRId64 " ns, "
4480 "early app phase %" PRId64 " ns, "
4481 "early sf phase %" PRId64 " ns, "
4482 "early app gl phase %" PRId64 " ns, "
4483 "early sf gl phase %" PRId64 " ns, "
4484 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4485 displayId,
4486 vsyncPhaseOffsetNs,
4487 sfVsyncPhaseOffsetNs,
4488 appEarlyOffset,
4489 sfEarlyOffset,
4490 appEarlyGlOffset,
4491 sfEarlyOffset,
4492 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004493 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004494 result.append("\n");
4495
Dan Stozab90cf072015-03-05 11:05:59 -08004496 // Dump static screen stats
4497 result.append("\n");
4498 dumpStaticScreenStats(result);
4499 result.append("\n");
4500
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004501 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4502
Dan Stozae77c7662016-05-13 11:37:28 -07004503 dumpBufferingStats(result);
4504
Andy McFadden4803b742012-09-24 19:07:20 -07004505 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004506 * Dump the visible layer list
4507 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004508 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004509 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004510 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4511 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004512 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004513
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004514 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004515 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004516 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004517 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004518
4519 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004520 * Dump Display state
4521 */
4522
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004523 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004524 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004525 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004526 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004527 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004528 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004529 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004530
4531 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004532 * Dump SurfaceFlinger global state
4533 */
4534
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004535 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004536 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004537 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004538
Mathias Agopian888c8222012-08-04 21:10:38 -07004539 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004540 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004541
David Sodmanbc815282017-11-05 18:57:52 -08004542 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004543
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004544 if (display) {
4545 display->undefinedRegion.dump(result, "undefinedRegion");
4546 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4547 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004548 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004549 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4550 " last transaction time : %f us\n"
4551 " transaction-flags : %08x\n"
4552 " gpu_to_cpu_unsupported : %d\n",
4553 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4554 mTransactionFlags, !mGpuToCpuSupported);
4555
4556 if (display) {
4557 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4558 result.appendFormat(" refresh-rate : %f fps\n"
4559 " x-dpi : %f\n"
4560 " y-dpi : %f\n",
4561 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4562 activeConfig->getDpiY());
4563 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004564
Mathias Agopian74d211a2013-04-22 16:55:35 +02004565 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004566 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004567
Mathias Agopian74d211a2013-04-22 16:55:35 +02004568 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004569 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004570
4571 /*
4572 * VSYNC state
4573 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004574 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004575 result.append("\n");
4576
4577 /*
4578 * HWC layer minidump
4579 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004580 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004581 const int32_t displayId = display->getId();
4582 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004583 continue;
4584 }
4585
Dominik Laskowski7e045462018-05-30 13:02:02 -07004586 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004587 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004588 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004589 result.append("\n");
4590 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004591
4592 /*
4593 * Dump HWComposer state
4594 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004595 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004596 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004597 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004598 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004599 result.appendFormat(" h/w composer %s\n",
4600 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004601 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004602
4603 /*
4604 * Dump gralloc state
4605 */
4606 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4607 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004608
4609 /*
4610 * Dump VrFlinger state if in use.
4611 */
4612 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4613 result.append("VrFlinger state:\n");
4614 result.append(mVrFlinger->Dump().c_str());
4615 result.append("\n");
4616 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004617}
4618
Dominik Laskowski7e045462018-05-30 13:02:02 -07004619const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004620 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004621 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004622 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004623 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004624 }
4625 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004626
4627 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4628 static const Vector<sp<Layer>> empty;
4629 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004630}
4631
Keun young Park63f165f2012-08-31 10:53:36 -07004632bool SurfaceFlinger::startDdmConnection()
4633{
4634 void* libddmconnection_dso =
4635 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4636 if (!libddmconnection_dso) {
4637 return false;
4638 }
4639 void (*DdmConnection_start)(const char* name);
4640 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004641 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004642 if (!DdmConnection_start) {
4643 dlclose(libddmconnection_dso);
4644 return false;
4645 }
4646 (*DdmConnection_start)(getServiceName());
4647 return true;
4648}
4649
Chia-I Wu28f320b2018-05-03 11:02:56 -07004650void SurfaceFlinger::updateColorMatrixLocked() {
4651 mat4 colorMatrix;
4652 if (mGlobalSaturationFactor != 1.0f) {
4653 // Rec.709 luma coefficients
4654 float3 luminance{0.213f, 0.715f, 0.072f};
4655 luminance *= 1.0f - mGlobalSaturationFactor;
4656 mat4 saturationMatrix = mat4(
4657 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4658 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4659 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4660 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4661 );
4662 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4663 } else {
4664 colorMatrix = mClientColorMatrix * mDaltonizer();
4665 }
4666
4667 if (mCurrentState.colorMatrix != colorMatrix) {
4668 mCurrentState.colorMatrix = colorMatrix;
4669 mCurrentState.colorMatrixChanged = true;
4670 setTransactionFlags(eTransactionNeeded);
4671 }
4672}
4673
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004674status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004675 switch (code) {
4676 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004677 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004678 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004679 case CLEAR_ANIMATION_FRAME_STATS:
4680 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004681 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004682 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004683 case ENABLE_VSYNC_INJECTIONS:
4684 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004685 {
4686 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004687 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4688 IPCThreadState* ipc = IPCThreadState::self();
4689 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4690 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004691 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004692 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004693 break;
4694 }
Robert Carr1db73f62016-12-21 12:58:51 -08004695 /*
4696 * Calling setTransactionState is safe, because you need to have been
4697 * granted a reference to Client* and Handle* to do anything with it.
4698 *
4699 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4700 */
4701 case SET_TRANSACTION_STATE:
4702 case CREATE_SCOPED_CONNECTION:
4703 {
4704 return OK;
4705 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004706 case CAPTURE_SCREEN:
4707 {
4708 // codes that require permission check
4709 IPCThreadState* ipc = IPCThreadState::self();
4710 const int pid = ipc->getCallingPid();
4711 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004712 if ((uid != AID_GRAPHICS) &&
4713 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004714 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004715 return PERMISSION_DENIED;
4716 }
4717 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004718 }
chaviwa76b2712017-09-20 12:02:26 -07004719 case CAPTURE_LAYERS: {
4720 IPCThreadState* ipc = IPCThreadState::self();
4721 const int pid = ipc->getCallingPid();
4722 const int uid = ipc->getCallingUid();
4723 if ((uid != AID_GRAPHICS) &&
4724 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4725 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4726 return PERMISSION_DENIED;
4727 }
4728 break;
4729 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004730 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004731 return OK;
4732}
4733
4734status_t SurfaceFlinger::onTransact(
4735 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4736{
4737 status_t credentialCheck = CheckTransactCodeCredentials(code);
4738 if (credentialCheck != OK) {
4739 return credentialCheck;
4740 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004741
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004742 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4743 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004744 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004745 IPCThreadState* ipc = IPCThreadState::self();
4746 const int uid = ipc->getCallingUid();
4747 if (CC_UNLIKELY(uid != AID_SYSTEM
4748 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004749 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004750 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004751 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004752 return PERMISSION_DENIED;
4753 }
4754 int n;
4755 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004756 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004757 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004758 return NO_ERROR;
4759 case 1002: // SHOW_UPDATES
4760 n = data.readInt32();
4761 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004762 invalidateHwcGeometry();
4763 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004764 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004765 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004766 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004767 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004768 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004769 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004770 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004771 setTransactionFlags(
4772 eTransactionNeeded|
4773 eDisplayTransactionNeeded|
4774 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004775 return NO_ERROR;
4776 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004777 case 1006:{ // send empty update
4778 signalRefresh();
4779 return NO_ERROR;
4780 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004781 case 1008: // toggle use of hw composer
4782 n = data.readInt32();
4783 mDebugDisableHWC = n ? 1 : 0;
4784 invalidateHwcGeometry();
4785 repaintEverything();
4786 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004787 case 1009: // toggle use of transform hint
4788 n = data.readInt32();
4789 mDebugDisableTransformHint = n ? 1 : 0;
4790 invalidateHwcGeometry();
4791 repaintEverything();
4792 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004793 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004794 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004795 reply->writeInt32(0);
4796 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004797 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004798 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004799 return NO_ERROR;
4800 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004801 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004802 if (!display) {
4803 return NAME_NOT_FOUND;
4804 }
4805
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004806 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004807 return NO_ERROR;
4808 }
4809 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004810 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004811 // daltonize
4812 n = data.readInt32();
4813 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004814 case 1:
4815 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4816 break;
4817 case 2:
4818 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4819 break;
4820 case 3:
4821 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4822 break;
4823 default:
4824 mDaltonizer.setType(ColorBlindnessType::None);
4825 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004826 }
4827 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004828 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004829 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004830 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004831 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004832
4833 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004834 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004835 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004836 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004837 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004838 // apply a color matrix
4839 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004840 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004841 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004842 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004843 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004844 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004845 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004846 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004847 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004848 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004849 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004850
4851 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4852 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004853 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004854 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4855 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4856 }
4857
Chia-I Wu28f320b2018-05-03 11:02:56 -07004858 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004859 return NO_ERROR;
4860 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004861 // This is an experimental interface
4862 // Needs to be shifted to proper binder interface when we productize
4863 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004864 n = data.readInt32();
4865 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004866 return NO_ERROR;
4867 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004868 case 1017: {
4869 n = data.readInt32();
4870 mForceFullDamage = static_cast<bool>(n);
4871 return NO_ERROR;
4872 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004873 case 1018: { // Modify Choreographer's phase offset
4874 n = data.readInt32();
4875 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4876 return NO_ERROR;
4877 }
4878 case 1019: { // Modify SurfaceFlinger's phase offset
4879 n = data.readInt32();
4880 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4881 return NO_ERROR;
4882 }
Irvel468051e2016-06-13 16:44:44 -07004883 case 1020: { // Layer updates interceptor
4884 n = data.readInt32();
4885 if (n) {
4886 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004887 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004888 }
4889 else{
4890 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004891 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004892 }
4893 return NO_ERROR;
4894 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004895 case 1021: { // Disable HWC virtual displays
4896 n = data.readInt32();
4897 mUseHwcVirtualDisplays = !n;
4898 return NO_ERROR;
4899 }
Romain Guy0147a172017-06-01 13:53:56 -07004900 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004901 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004902 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004903
Chia-I Wu28f320b2018-05-03 11:02:56 -07004904 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004905 return NO_ERROR;
4906 }
Romain Guy54f154a2017-10-24 21:40:32 +01004907 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004908 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004909 invalidateHwcGeometry();
4910 repaintEverything();
4911 return NO_ERROR;
4912 }
4913 case 1024: { // Is wide color gamut rendering/color management supported?
4914 reply->writeBool(hasWideColorDisplay);
4915 return NO_ERROR;
4916 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004917 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004918 n = data.readInt32();
4919 if (n) {
4920 ALOGV("LayerTracing enabled");
4921 mTracing.enable();
4922 doTracing("tracing.enable");
4923 reply->writeInt32(NO_ERROR);
4924 } else {
4925 ALOGV("LayerTracing disabled");
4926 status_t err = mTracing.disable();
4927 reply->writeInt32(err);
4928 }
4929 return NO_ERROR;
4930 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004931 case 1026: { // Get layer tracing status
4932 reply->writeBool(mTracing.isEnabled());
4933 return NO_ERROR;
4934 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004935 // Is a DisplayColorSetting supported?
4936 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004937 const auto display = getDefaultDisplayDevice();
4938 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004939 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004940 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004941
4942 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4943 switch (setting) {
4944 case DisplayColorSetting::MANAGED:
4945 reply->writeBool(hasWideColorDisplay);
4946 break;
4947 case DisplayColorSetting::UNMANAGED:
4948 reply->writeBool(true);
4949 break;
4950 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004951 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004952 break;
4953 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004954 reply->writeBool(
4955 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004956 break;
4957 }
4958 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004959 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004960 // Is VrFlinger active?
4961 case 1028: {
4962 Mutex::Autolock _l(mStateLock);
4963 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4964 return NO_ERROR;
4965 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004966 }
4967 }
4968 return err;
4969}
4970
Steven Thomas6d8110b2017-08-31 18:24:21 -07004971void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004972 android_atomic_or(1, &mRepaintEverything);
4973 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004974}
4975
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004976// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4977class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004978public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004979 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4980 ~WindowDisconnector() {
4981 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004982 }
4983
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004984private:
4985 ANativeWindow* mWindow;
4986 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004987};
4988
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004989status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4990 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4991 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4992 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004993 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004994 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004995
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004996 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004997
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004998 const auto display = getDisplayDeviceLocked(displayToken);
4999 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005000
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005001 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07005002
5003 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005004 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005005 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005006}
5007
5008status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005009 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005010 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005011 ATRACE_CALL();
5012
5013 class LayerRenderArea : public RenderArea {
5014 public:
Robert Carr578038f2018-03-09 12:25:24 -08005015 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5016 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07005017 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005018 mLayer(layer),
5019 mCrop(crop),
5020 mFlinger(flinger),
5021 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005022 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005023 Rect getBounds() const override {
5024 const Layer::State& layerState(mLayer->getDrawingState());
5025 return Rect(layerState.active.w, layerState.active.h);
5026 }
5027 int getHeight() const override { return mLayer->getDrawingState().active.h; }
5028 int getWidth() const override { return mLayer->getDrawingState().active.w; }
5029 bool isSecure() const override { return false; }
5030 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005031 Rect getSourceCrop() const override {
5032 if (mCrop.isEmpty()) {
5033 return getBounds();
5034 } else {
5035 return mCrop;
5036 }
5037 }
Robert Carr578038f2018-03-09 12:25:24 -08005038 class ReparentForDrawing {
5039 public:
5040 const sp<Layer>& oldParent;
5041 const sp<Layer>& newParent;
5042
5043 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5044 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005045 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005046 }
Robert Carr15eae092018-03-23 13:43:53 -07005047 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005048 };
5049
5050 void render(std::function<void()> drawLayers) override {
5051 if (!mChildrenOnly) {
5052 mTransform = mLayer->getTransform().inverse();
5053 drawLayers();
5054 } else {
5055 Rect bounds = getBounds();
5056 screenshotParentLayer =
5057 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5058 bounds.getWidth(), bounds.getHeight(), 0);
5059
5060 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5061 drawLayers();
5062 }
5063 }
chaviwa76b2712017-09-20 12:02:26 -07005064
chaviwa76b2712017-09-20 12:02:26 -07005065 private:
chaviw7206d492017-11-10 16:16:12 -08005066 const sp<Layer> mLayer;
5067 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005068
5069 // In the "childrenOnly" case we reparent the children to a screenshot
5070 // layer which has no properties set and which does not draw.
5071 sp<ContainerLayer> screenshotParentLayer;
5072 Transform mTransform;
5073
5074 SurfaceFlinger* mFlinger;
5075 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005076 };
5077
5078 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5079 auto parent = layerHandle->owner.promote();
5080
chaviw7206d492017-11-10 16:16:12 -08005081 if (parent == nullptr || parent->isPendingRemoval()) {
5082 ALOGE("captureLayers called with a removed parent");
5083 return NAME_NOT_FOUND;
5084 }
5085
Robert Carr578038f2018-03-09 12:25:24 -08005086 const int uid = IPCThreadState::self()->getCallingUid();
5087 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5088 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5089 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5090 return PERMISSION_DENIED;
5091 }
5092
chaviw7206d492017-11-10 16:16:12 -08005093 Rect crop(sourceCrop);
5094 if (sourceCrop.width() <= 0) {
5095 crop.left = 0;
5096 crop.right = parent->getCurrentState().active.w;
5097 }
5098
5099 if (sourceCrop.height() <= 0) {
5100 crop.top = 0;
5101 crop.bottom = parent->getCurrentState().active.h;
5102 }
5103
5104 int32_t reqWidth = crop.width() * frameScale;
5105 int32_t reqHeight = crop.height() * frameScale;
5106
Robert Carr578038f2018-03-09 12:25:24 -08005107 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005108
Robert Carr578038f2018-03-09 12:25:24 -08005109 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005110 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5111 if (!layer->isVisible()) {
5112 return;
Robert Carr578038f2018-03-09 12:25:24 -08005113 } else if (childrenOnly && layer == parent.get()) {
5114 return;
chaviwa76b2712017-09-20 12:02:26 -07005115 }
5116 visitor(layer);
5117 });
5118 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005119 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005120}
5121
5122status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5123 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005124 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005125 bool useIdentityTransform) {
5126 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005127
Iris Chang7501ed62018-04-30 14:45:42 +08005128 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005129
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005130 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5131 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5132 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5133 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005134
5135 // This mutex protects syncFd and captureResult for communication of the return values from the
5136 // main thread back to this Binder thread
5137 std::mutex captureMutex;
5138 std::condition_variable captureCondition;
5139 std::unique_lock<std::mutex> captureLock(captureMutex);
5140 int syncFd = -1;
5141 std::optional<status_t> captureResult;
5142
Robert Carr03480e22018-01-04 16:02:06 -08005143 const int uid = IPCThreadState::self()->getCallingUid();
5144 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5145
Dominik Laskowski8c001672018-05-30 16:52:06 -07005146 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005147 // If there is a refresh pending, bug out early and tell the binder thread to try again
5148 // after the refresh.
5149 if (mRefreshPending) {
5150 ATRACE_NAME("Skipping screenshot for now");
5151 std::unique_lock<std::mutex> captureLock(captureMutex);
5152 captureResult = std::make_optional<status_t>(EAGAIN);
5153 captureCondition.notify_one();
5154 return;
5155 }
5156
5157 status_t result = NO_ERROR;
5158 int fd = -1;
5159 {
5160 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005161 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005162 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5163 useIdentityTransform, forSystem, &fd);
5164 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005165 }
5166
5167 {
5168 std::unique_lock<std::mutex> captureLock(captureMutex);
5169 syncFd = fd;
5170 captureResult = std::make_optional<status_t>(result);
5171 captureCondition.notify_one();
5172 }
5173 });
5174
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005175 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005176 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005177 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005178 while (*captureResult == EAGAIN) {
5179 captureResult.reset();
5180 result = postMessageAsync(message);
5181 if (result != NO_ERROR) {
5182 return result;
5183 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005184 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005185 }
5186 result = *captureResult;
5187 }
5188
5189 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005190 sync_wait(syncFd, -1);
5191 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005192 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005193
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005194 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005195}
5196
chaviwa76b2712017-09-20 12:02:26 -07005197void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5198 TraverseLayersFunction traverseLayers, bool yswap,
5199 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005200 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005201
Lloyd Pique144e1162017-12-20 16:44:52 -08005202 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005203
5204 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005205 const auto raWidth = renderArea.getWidth();
5206 const auto raHeight = renderArea.getHeight();
5207
5208 const auto reqWidth = renderArea.getReqWidth();
5209 const auto reqHeight = renderArea.getReqHeight();
5210 Rect sourceCrop = renderArea.getSourceCrop();
5211
Iris Chang7501ed62018-04-30 14:45:42 +08005212 bool filtering = false;
5213 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5214 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5215 static_cast<int32_t>(reqHeight) != raWidth;
5216 } else {
5217 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5218 static_cast<int32_t>(reqHeight) != raHeight;
5219 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005220
Dan Stozac1879002014-05-22 15:59:05 -07005221 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005222 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005223 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005224 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005225 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5226 Transform tr;
5227 uint32_t flags = 0x00;
5228 switch (mPrimaryDisplayOrientation) {
5229 case DisplayState::eOrientation90:
5230 flags = Transform::ROT_90;
5231 break;
5232 case DisplayState::eOrientation180:
5233 flags = Transform::ROT_180;
5234 break;
5235 case DisplayState::eOrientation270:
5236 flags = Transform::ROT_270;
5237 break;
5238 }
5239 tr.set(flags, raWidth, raHeight);
5240 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005241 }
5242
5243 // ensure that sourceCrop is inside screen
5244 if (sourceCrop.left < 0) {
5245 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5246 }
chaviwa76b2712017-09-20 12:02:26 -07005247 if (sourceCrop.right > raWidth) {
5248 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005249 }
5250 if (sourceCrop.top < 0) {
5251 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5252 }
chaviwa76b2712017-09-20 12:02:26 -07005253 if (sourceCrop.bottom > raHeight) {
5254 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005255 }
5256
Chia-I Wu36574d92018-05-16 10:54:36 -07005257 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5258 engine.setOutputDataSpace(Dataspace::SRGB);
5259 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005260
Mathias Agopian180f10d2013-04-10 22:55:41 -07005261 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005262 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005263
Iris Chang7501ed62018-04-30 14:45:42 +08005264 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5265 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5266 // convert hw orientation into flag presentation
5267 // here inverse transform needed
5268 uint8_t hw_rot_90 = 0x00;
5269 uint8_t hw_flip_hv = 0x00;
5270 switch (mPrimaryDisplayOrientation) {
5271 case DisplayState::eOrientation90:
5272 hw_rot_90 = Transform::ROT_90;
5273 hw_flip_hv = Transform::ROT_180;
5274 break;
5275 case DisplayState::eOrientation180:
5276 hw_flip_hv = Transform::ROT_180;
5277 break;
5278 case DisplayState::eOrientation270:
5279 hw_rot_90 = Transform::ROT_90;
5280 break;
5281 }
5282
5283 // transform flags operation
5284 // 1) flip H V if both have ROT_90 flag
5285 // 2) XOR these flags
5286 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5287 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5288 if (rotation_rot_90 & hw_rot_90) {
5289 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5290 }
5291 rotation = static_cast<Transform::orientation_flags>
5292 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5293 }
5294
Mathias Agopian180f10d2013-04-10 22:55:41 -07005295 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005296 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005297 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005298 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005299
chaviw50da5042018-04-09 13:49:37 -07005300 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005301 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005302 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005303
chaviwa76b2712017-09-20 12:02:26 -07005304 traverseLayers([&](Layer* layer) {
5305 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005306 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005307 if (filtering) layer->setFiltering(false);
5308 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005309}
5310
chaviwa76b2712017-09-20 12:02:26 -07005311status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5312 TraverseLayersFunction traverseLayers,
5313 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005314 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005315 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005316 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005317 ATRACE_CALL();
5318
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005319 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005320
5321 traverseLayers([&](Layer* layer) {
5322 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5323 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005324
Robert Carr03480e22018-01-04 16:02:06 -08005325 // We allow the system server to take screenshots of secure layers for
5326 // use in situations like the Screen-rotation animation and place
5327 // the impetus on WindowManager to not persist them.
5328 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005329 ALOGW("FB is protected: PERMISSION_DENIED");
5330 return PERMISSION_DENIED;
5331 }
5332
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005333 // this binds the given EGLImage as a framebuffer for the
5334 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005335 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005336 if (bufferBond.getStatus() != NO_ERROR) {
5337 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005338 return INVALID_OPERATION;
5339 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005340
Dan Stozaabcda352017-06-01 14:37:39 -07005341 // this will in fact render into our dequeued buffer
5342 // via an FBO, which means we didn't have to create
5343 // an EGLSurface and therefore we're not
5344 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005345 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005346
Dan Stozaabcda352017-06-01 14:37:39 -07005347 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005348 getRenderEngine().finish();
5349 *outSyncFd = -1;
5350
chaviwa76b2712017-09-20 12:02:26 -07005351 const auto reqWidth = renderArea.getReqWidth();
5352 const auto reqHeight = renderArea.getReqHeight();
5353
Dan Stozaabcda352017-06-01 14:37:39 -07005354 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5355 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005356 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005357 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005358 } else {
5359 base::unique_fd syncFd = getRenderEngine().flush();
5360 if (syncFd < 0) {
5361 getRenderEngine().finish();
5362 }
5363 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005364 }
5365
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005366 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005367}
5368
Mathias Agopiand5556842013-09-19 17:08:37 -07005369void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005370 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005371 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005372 for (size_t y = 0; y < h; y++) {
5373 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5374 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005375 if (p[x] != 0xFF000000) return;
5376 }
5377 }
chaviwa76b2712017-09-20 12:02:26 -07005378 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005379
Robert Carr2047fae2016-11-28 14:09:09 -08005380 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005381 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005382 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005383 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5384 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5385 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5386 static_cast<float>(state.color.a));
5387 i++;
5388 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005389 }
5390}
5391
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005392// ---------------------------------------------------------------------------
5393
Dan Stoza412903f2017-04-27 13:42:17 -07005394void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5395 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005396}
5397
Dan Stoza412903f2017-04-27 13:42:17 -07005398void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5399 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005400}
5401
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005402void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5403 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005404 const LayerVector::Visitor& visitor) {
5405 // We loop through the first level of layers without traversing,
5406 // as we need to interpret min/max layer Z in the top level Z space.
5407 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005408 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005409 continue;
5410 }
5411 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005412 // relative layers are traversed in Layer::traverseInZOrder
5413 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005414 continue;
5415 }
5416 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005417 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005418 return;
5419 }
chaviwa76b2712017-09-20 12:02:26 -07005420 if (!layer->isVisible()) {
5421 return;
5422 }
5423 visitor(layer);
5424 });
5425 }
5426}
5427
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005428}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005429
Mathias Agopian3f844832013-08-07 21:24:32 -07005430#if defined(__gl_h_)
5431#error "don't include gl/gl.h in this file"
5432#endif
5433
5434#if defined(__gl2_h_)
5435#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005436#endif