blob: 7da01c901e0e43edf64e746f22c87e0357a17f58 [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);
Chia-I Wu11d10612018-06-21 15:41:13 +0800354 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 Thomasdfde8fa2018-04-19 16:00:58 -07001358 ATRACE_NAME("SF onVsync");
1359
Steven Thomas3cfac282017-02-06 12:29:30 -08001360 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001361 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001362 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001363 return;
1364 }
1365
1366 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001367 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001368 return;
1369 }
1370
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001371 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1372 // For now, we don't do anything with external display vsyncs.
1373 return;
1374 }
1375
Jamie Gennisd1700752013-10-14 12:22:52 -07001376 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001377
Jamie Gennisd1700752013-10-14 12:22:52 -07001378 { // Scope for the lock
1379 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001380 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001381 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001382 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001383 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001384
1385 if (needsHwVsync) {
1386 enableHardwareVsync();
1387 } else {
1388 disableHardwareVsync(false);
1389 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001390}
1391
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001392void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001393 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1394 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001395}
1396
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001397void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001398 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001399 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001400 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001401
Lloyd Piqueba04e622017-12-14 17:11:26 -08001402 // Ignore events that do not have the right sequenceId.
1403 if (sequenceId != getBE().mComposerSequenceId) {
1404 return;
1405 }
1406
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 // Only lock if we're not on the main thread. This function is normally
1408 // called on a hwbinder thread, but for the primary display it's called on
1409 // the main thread with the state lock already held, so don't attempt to
1410 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001411 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001412
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001413 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001414
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001415 if (std::this_thread::get_id() == mMainThreadId) {
1416 // Process all pending hot plug events immediately if we are on the main thread.
1417 processDisplayHotplugEventsLocked();
1418 }
1419
Lloyd Piqueba04e622017-12-14 17:11:26 -08001420 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001421}
1422
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001423void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001424 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001425 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001426 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001427 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001428 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001429}
1430
Dan Stoza9e56aa02015-11-02 13:00:03 -08001431void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001432 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001433 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001434 getHwComposer().setVsyncEnabled(disp,
1435 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001436}
1437
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001438// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001439void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001440 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001441 // Clear the drawing state so that the logic inside of
1442 // handleTransactionLocked will fire. It will determine the delta between
1443 // mCurrentState and mDrawingState and re-apply all changes when we make the
1444 // transition.
1445 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001446 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001447 mDisplays.clear();
1448}
1449
Steven Thomas050b2c82017-03-06 11:45:16 -08001450void SurfaceFlinger::updateVrFlinger() {
1451 if (!mVrFlinger)
1452 return;
1453 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001454 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001455 return;
1456 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001457
David Sodman105b7dc2017-11-04 20:28:14 -07001458 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001459 ALOGE("Vr flinger is only supported for remote hardware composer"
1460 " service connections. Ignoring request to transition to vr"
1461 " flinger.");
1462 mVrFlingerRequestsDisplay = false;
1463 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001464 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001465
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001466 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001467
Steven Thomas0123ac62018-07-12 11:32:34 -07001468 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001469 LOG_ALWAYS_FATAL_IF(!display);
1470 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001471 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1472 // called below. Clear the reference now so we don't accidentally use it
1473 // later.
1474 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001475
Steven Thomasb02664d2017-07-26 18:48:28 -07001476 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001477 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001478 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001479
Steven Thomasb02664d2017-07-26 18:48:28 -07001480 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001481 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001482 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1483 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001484 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001485
David Sodman105b7dc2017-11-04 20:28:14 -07001486 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1487 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001488
1489 if (vrFlingerRequestsDisplay) {
1490 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001491 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001492
1493 mVisibleRegionsDirty = true;
1494 invalidateHwcGeometry();
1495
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001496 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001497 display = getDefaultDisplayDeviceLocked();
1498 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001499 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001500
Steven Thomasb02664d2017-07-26 18:48:28 -07001501 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001502 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001503 const nsecs_t period = activeConfig->getVsyncPeriod();
1504 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001505
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001506 // The present fences returned from vr_hwc are not an accurate
1507 // representation of vsync times.
1508 mPrimaryDispSync.setIgnorePresentFences(
1509 getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1510
Steven Thomasb02664d2017-07-26 18:48:28 -07001511 // Use phase of 0 since phase is not known.
1512 // Use latency of 0, which will snap to the ideal latency.
1513 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001514
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001515 resyncToHardwareVsync(false);
1516
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001517 android_atomic_or(1, &mRepaintEverything);
1518 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001519}
1520
Mathias Agopian4fec8732012-06-29 14:12:52 -07001521void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001522 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001523 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001524 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001525 bool frameMissed = !mHadClientComposition &&
1526 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001527 (mPreviousPresentFence->getSignalTime() ==
1528 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001529 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001530 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001531 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001532 mTimeStats.incrementMissedFrames();
1533 if (mPropagateBackpressure) {
1534 signalLayerUpdate();
1535 break;
1536 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001537 }
Dan Stoza50182882016-07-08 12:02:20 -07001538
Steven Thomas050b2c82017-03-06 11:45:16 -08001539 // Now that we're going to make it to the handleMessageTransaction()
1540 // call below it's safe to call updateVrFlinger(), which will
1541 // potentially trigger a display handoff.
1542 updateVrFlinger();
1543
Dan Stoza6b9454d2014-11-07 16:00:59 -08001544 bool refreshNeeded = handleMessageTransaction();
1545 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001546 refreshNeeded |= mRepaintEverything;
David Sodman0756cdd2018-04-13 11:26:33 -07001547
1548 preComposition();
1549 rebuildLayerStacks();
1550 calculateWorkingSet();
1551
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001552 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
David Sodman0756cdd2018-04-13 11:26:33 -07001553
Dan Stoza58784442014-12-02 16:58:17 -08001554 // Signal a refresh if a transaction modified the window state,
1555 // a new buffer was latched, or if HWC has requested a full
1556 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001557 signalRefresh();
1558 }
1559 break;
1560 }
1561 case MessageQueue::REFRESH: {
1562 handleMessageRefresh();
1563 break;
1564 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001565 }
1566}
1567
Dan Stoza6b9454d2014-11-07 16:00:59 -08001568bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001569 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001570 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001571 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001572 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001573 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001574 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001575}
1576
Dan Stoza6b9454d2014-11-07 16:00:59 -08001577bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001578 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001579 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001580}
1581
David Sodman0756cdd2018-04-13 11:26:33 -07001582void SurfaceFlinger::calculateWorkingSet() {
1583 ATRACE_CALL();
1584 ALOGV(__FUNCTION__);
1585
1586 // build the h/w work list
1587 if (CC_UNLIKELY(mGeometryInvalid)) {
1588 mGeometryInvalid = false;
1589 for (const auto& [token, display] : mDisplays) {
1590 const auto displayId = display->getId();
1591 if (displayId >= 0) {
1592 const Vector<sp<Layer>>& currentLayers(
1593 display->getVisibleLayersSortedByZ());
1594 for (size_t i = 0; i < currentLayers.size(); i++) {
1595 const auto& layer = currentLayers[i];
1596
1597 if (!layer->hasHwcLayer(displayId)) {
1598 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1599 layer->forceClientComposition(displayId);
1600 continue;
1601 }
1602 }
1603
1604 layer->setGeometry(display, i);
1605 if (mDebugDisableHWC || mDebugRegion) {
1606 layer->forceClientComposition(displayId);
1607 }
1608 }
1609 }
1610 }
1611 }
1612
1613 // Set the per-frame data
1614 for (const auto& [token, display] : mDisplays) {
1615 const auto displayId = display->getId();
1616 if (displayId < 0) {
1617 continue;
1618 }
1619
1620 if (mDrawingState.colorMatrixChanged) {
1621 display->setColorTransform(mDrawingState.colorMatrix);
1622 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1623 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1624 "display %d: %d", displayId, result);
1625 }
1626 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1627 if (layer->isHdrY410()) {
1628 layer->forceClientComposition(displayId);
1629 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1630 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1631 !display->hasHDR10Support()) {
1632 layer->forceClientComposition(displayId);
1633 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1634 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1635 !display->hasHLGSupport()) {
1636 layer->forceClientComposition(displayId);
1637 }
1638
1639 if (layer->getForceClientComposition(displayId)) {
1640 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1641 layer->setCompositionType(displayId, HWC2::Composition::Client);
1642 continue;
1643 }
1644
1645 layer->setPerFrameData(display);
1646 }
1647
1648 if (hasWideColorDisplay) {
1649 ColorMode colorMode;
1650 Dataspace dataSpace;
1651 RenderIntent renderIntent;
1652 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1653 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1654 }
1655 }
1656
1657 mDrawingState.colorMatrixChanged = false;
1658 getBE().mCompositionInfo.clear();
1659
1660 for (const auto& [token, display] : mDisplays) {
1661 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1662 auto displayId = display->getId();
1663 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1664 if (!layer->setHwcLayer(displayId)) {
1665 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1666 }
1667 getBE().mCompositionInfo.push_back(layer->getBE().compositionInfo);
1668 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1669 }
1670 }
1671}
1672
Mathias Agopian4fec8732012-06-29 14:12:52 -07001673void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001674 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001675
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001676 mRefreshPending = false;
1677
David Sodman0756cdd2018-04-13 11:26:33 -07001678 beginFrame();
1679 for (auto compositionInfo : getBE().mCompositionInfo) {
1680 setUpHWComposer(compositionInfo);
1681 }
1682 prepareFrame();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001683 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001684 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001685 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001686 doComposition();
David Sodman0756cdd2018-04-13 11:26:33 -07001687 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001688
Dan Stozabfbffeb2016-07-21 14:49:33 -07001689 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001690 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001691 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001692 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001693 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001694 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001695
Dan Stoza9e56aa02015-11-02 13:00:03 -08001696 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001697}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001698
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699void SurfaceFlinger::doDebugFlashRegions()
1700{
1701 // is debugging enabled
1702 if (CC_LIKELY(!mDebugRegion))
1703 return;
1704
1705 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001706 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001707 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001708 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001709 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001710 if (!dirtyRegion.isEmpty()) {
1711 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001712 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001713
1714 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001715 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001716 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001717 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1718
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001719 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001720 }
1721 }
1722 }
1723
1724 postFramebuffer();
1725
1726 if (mDebugRegion > 1) {
1727 usleep(mDebugRegion * 1000);
1728 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001729
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001730 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001731 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001732 continue;
1733 }
1734
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001735 status_t result = display->prepareFrame(*getBE().mHwc);
1736 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001737 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001738 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001739}
1740
Adrian Roos1e1a1282017-11-01 19:05:31 +01001741void SurfaceFlinger::doTracing(const char* where) {
1742 ATRACE_CALL();
1743 ATRACE_NAME(where);
1744 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001745 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001746 }
1747}
1748
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001749void SurfaceFlinger::logLayerStats() {
1750 ATRACE_CALL();
1751 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001752 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001753 if (display->isPrimary()) {
1754 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001755 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001756 }
1757 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001758
1759 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001760 }
1761}
1762
David Sodman0756cdd2018-04-13 11:26:33 -07001763void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001764{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001765 ATRACE_CALL();
1766 ALOGV("preComposition");
1767
Mathias Agopiancd60f992012-08-16 16:28:27 -07001768 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001769 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman0756cdd2018-04-13 11:26:33 -07001770 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001771 needExtraInvalidate = true;
1772 }
Robert Carr2047fae2016-11-28 14:09:09 -08001773 });
1774
Mathias Agopiancd60f992012-08-16 16:28:27 -07001775 if (needExtraInvalidate) {
1776 signalLayerUpdate();
1777 }
1778}
1779
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001780void SurfaceFlinger::updateCompositorTiming(
1781 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1782 std::shared_ptr<FenceTime>& presentFenceTime) {
1783 // Update queue of past composite+present times and determine the
1784 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001785 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001786 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001787 while (!getBE().mCompositePresentTimes.empty()) {
1788 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001789 // Cached values should have been updated before calling this method,
1790 // which helps avoid duplicate syscalls.
1791 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1792 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1793 break;
1794 }
1795 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001796 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001797 }
1798
1799 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001800 while (getBE().mCompositePresentTimes.size() > 16) {
1801 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001802 }
1803
Brian Andersond0010582017-03-07 13:20:31 -08001804 setCompositorTimingSnapped(
1805 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1806}
1807
1808void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1809 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001810 // Integer division and modulo round toward 0 not -inf, so we need to
1811 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001812 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001813 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1814 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1815
Brian Andersond0010582017-03-07 13:20:31 -08001816 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1817 if (idealLatency <= 0) {
1818 idealLatency = vsyncInterval;
1819 }
1820
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001821 // Snap the latency to a value that removes scheduling jitter from the
1822 // composition and present times, which often have >1ms of jitter.
1823 // Reducing jitter is important if an app attempts to extrapolate
1824 // something (such as user input) to an accurate diasplay time.
1825 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1826 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001827 nsecs_t bias = vsyncInterval / 2;
1828 int64_t extraVsyncs =
1829 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1830 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1831 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001832
David Sodman99974d22017-11-28 12:04:33 -08001833 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1834 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1835 getBE().mCompositorTiming.interval = vsyncInterval;
1836 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001837}
1838
David Sodman0756cdd2018-04-13 11:26:33 -07001839void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001840{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001841 ATRACE_CALL();
1842 ALOGV("postComposition");
1843
Brian Anderson3546a3f2016-07-14 11:51:14 -07001844 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001845 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001846 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001847 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001848 }
1849
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001850 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001851 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001852
David Sodman73beded2017-11-15 11:56:06 -08001853 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001854 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001855 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001856 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001857 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001858 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001859 } else {
1860 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1861 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001862
David Sodman73beded2017-11-15 11:56:06 -08001863 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001864 mPreviousPresentFence =
1865 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1866 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001867 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001868
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001869 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1870 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1871
David Sodman0756cdd2018-04-13 11:26:33 -07001872 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001873 // when we started doing work for this frame, but that should be okay
1874 // since updateCompositorTiming has snapping logic.
1875 updateCompositorTiming(
David Sodman0756cdd2018-04-13 11:26:33 -07001876 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001877 CompositorTiming compositorTiming;
1878 {
David Sodman99974d22017-11-28 12:04:33 -08001879 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1880 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001881 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001882
Robert Carr2047fae2016-11-28 14:09:09 -08001883 mDrawingState.traverseInZOrder([&](Layer* layer) {
1884 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001885 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001886 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001887 recordBufferingStats(layer->getName().string(),
1888 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001889 }
Robert Carr2047fae2016-11-28 14:09:09 -08001890 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001891
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001892 if (presentFenceTime->isValid()) {
1893 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001894 enableHardwareVsync();
1895 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001896 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001897 }
1898 }
1899
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001900 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001901 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001902 enableHardwareVsync();
1903 }
1904 }
1905
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001906 if (mAnimCompositionPending) {
1907 mAnimCompositionPending = false;
1908
Brian Anderson4e606e32017-03-16 15:34:57 -07001909 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001910 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001911 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001912 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001913 // The HWC doesn't support present fences, so use the refresh
1914 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001915 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001916 mAnimFrameTracker.setActualPresentTime(presentTime);
1917 }
1918 mAnimFrameTracker.advanceFrame();
1919 }
Dan Stozab90cf072015-03-05 11:05:59 -08001920
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001921 mTimeStats.incrementTotalFrames();
1922 if (mHadClientComposition) {
1923 mTimeStats.incrementClientCompositionFrames();
1924 }
1925
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001926 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001927 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001928 return;
1929 }
1930
1931 nsecs_t currentTime = systemTime();
1932 if (mHasPoweredOff) {
1933 mHasPoweredOff = false;
1934 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001935 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001936 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001937 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1938 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001939 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001940 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001941 }
David Sodman4a36e932017-11-07 14:29:47 -08001942 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001943 }
David Sodman4a36e932017-11-07 14:29:47 -08001944 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001945
1946 {
1947 std::lock_guard lock(mTexturePoolMutex);
1948 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1949 if (refillCount > 0) {
1950 const size_t offset = mTexturePool.size();
1951 mTexturePool.resize(mTexturePoolSize);
1952 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1953 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1954 }
1955 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001956}
1957
1958void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001959 ATRACE_CALL();
1960 ALOGV("rebuildLayerStacks");
1961
Mathias Agopiancd60f992012-08-16 16:28:27 -07001962 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001963 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001964 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001965 mVisibleRegionsDirty = false;
1966 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001967
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001968 for (const auto& pair : mDisplays) {
1969 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001970 Region opaqueRegion;
1971 Region dirtyRegion;
1972 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001973 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001974 const Transform& tr = display->getTransform();
1975 const Rect bounds = display->getBounds();
1976 if (display->isPoweredOn()) {
1977 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001978
Jeff Sharkey76488112017-02-27 14:15:18 -07001979 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001980 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001981 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001982 Region drawRegion(tr.transform(
1983 layer->visibleNonTransparentRegion));
1984 drawRegion.andSelf(bounds);
1985 if (!drawRegion.isEmpty()) {
1986 layersSortedByZ.add(layer);
1987 } else {
David Sodman0756cdd2018-04-13 11:26:33 -07001988 if (layer->hasHwcLayer(display->getId())) {
1989 // Clear out the HWC layer if this layer was
1990 // previously visible, but no longer is
1991 hwcLayerDestroyed = layer->destroyHwcLayer(
1992 display->getId());
1993 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001994 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001995 } else {
David Sodman0756cdd2018-04-13 11:26:33 -07001996 if (layer->hasHwcLayer(display->getId())) {
1997 // WM changes display->layerStack upon sleep/awake.
1998 // Here we make sure we delete the HWC layers even if
1999 // WM changed their layer stack.
2000 hwcLayerDestroyed = layer->destroyHwcLayer(
2001 display->getId());
2002 }
Chia-I Wu83806892017-11-16 10:50:20 -08002003 }
2004
2005 // If a layer is not going to get a release fence because
2006 // it is invisible, but it is also going to release its
2007 // old buffer, add it to the list of layers needing
2008 // fences.
2009 if (hwcLayerDestroyed) {
2010 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2011 mLayersWithQueuedFrames.cend(), layer);
2012 if (found != mLayersWithQueuedFrames.cend()) {
2013 layersNeedingFences.add(layer);
2014 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002015 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002016 });
2017 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002018 display->setVisibleLayersSortedByZ(layersSortedByZ);
2019 display->setLayersNeedingFences(layersNeedingFences);
2020 display->undefinedRegion.set(bounds);
2021 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2022 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002023 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002024 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002025}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002026
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002027// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002028// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002029// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002030// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002031// The returned HDR data space is one of
2032// - Dataspace::UNKNOWN
2033// - Dataspace::BT2020_HLG
2034// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002035Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2036 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002037 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002038 *outHdrDataSpace = Dataspace::UNKNOWN;
2039
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002040 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002041 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002042 case Dataspace::V0_SCRGB:
2043 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002044 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002045 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002046 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002047 case Dataspace::BT2020_PQ:
2048 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002049 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002050 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002051 case Dataspace::BT2020_HLG:
2052 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002053 // When there's mixed PQ content and HLG content, we set the HDR
2054 // data space to be BT2020_PQ and convert HLG to PQ.
2055 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2056 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002057 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002058 break;
2059 default:
2060 break;
2061 }
Romain Guy54f154a2017-10-24 21:40:32 +01002062 }
2063
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002064 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002065}
2066
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002067// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002068void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2069 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002070 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2071 *outMode = ColorMode::NATIVE;
2072 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002073 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002074 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002075 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002076
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002077 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002078 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002079
Peiyong Lindfde5112018-06-05 10:58:41 -07002080 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002081 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002082 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002083 if (isHdr) {
2084 bestDataSpace = hdrDataSpace;
2085 }
2086
Chia-I Wu0d711262018-05-21 15:19:35 -07002087 RenderIntent intent;
2088 switch (mDisplayColorSetting) {
2089 case DisplayColorSetting::MANAGED:
2090 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002091 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002092 break;
2093 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002094 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002095 break;
2096 default: // vendor display color setting
2097 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2098 break;
2099 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002100
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002101 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002102}
2103
David Sodman0756cdd2018-04-13 11:26:33 -07002104void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2105{
2106 HWC2::Error error;
2107 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2108 "CompositionType is sideband, but sideband stream is nullptr");
2109 error = (compositionInfo.hwc.hwcLayer)
2110 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2111 if (error != HWC2::Error::None) {
2112 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2113 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2114 static_cast<int32_t>(error));
2115 }
2116}
2117
2118void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2119{
2120 HWC2::Error error;
2121
2122 if (!compositionInfo.hwc.skipGeometry) {
2123 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2124 ALOGE_IF(error != HWC2::Error::None,
2125 "[SF] Failed to set blend mode %s:"
2126 " %s (%d)",
2127 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2128 static_cast<int32_t>(error));
2129
2130 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2131 ALOGE_IF(error != HWC2::Error::None,
2132 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2133 compositionInfo.hwc.displayFrame.left,
2134 compositionInfo.hwc.displayFrame.right,
2135 compositionInfo.hwc.displayFrame.top,
2136 compositionInfo.hwc.displayFrame.bottom,
2137 to_string(error).c_str(), static_cast<int32_t>(error));
2138
2139 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2140 ALOGE_IF(error != HWC2::Error::None,
2141 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2142 compositionInfo.hwc.sourceCrop.left,
2143 compositionInfo.hwc.sourceCrop.right,
2144 compositionInfo.hwc.sourceCrop.top,
2145 compositionInfo.hwc.sourceCrop.bottom,
2146 to_string(error).c_str(), static_cast<int32_t>(error));
2147
2148 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2149 ALOGE_IF(error != HWC2::Error::None,
2150 "[SF] Failed to set plane alpha %.3f: "
2151 "%s (%d)",
2152 compositionInfo.hwc.alpha,
2153 to_string(error).c_str(), static_cast<int32_t>(error));
2154
2155
2156 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2157 ALOGE_IF(error != HWC2::Error::None,
2158 "[SF] Failed to set Z %u: %s (%d)",
2159 compositionInfo.hwc.z,
2160 to_string(error).c_str(), static_cast<int32_t>(error));
2161
2162 error = (compositionInfo.hwc.hwcLayer)
2163 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2164 ALOGE_IF(error != HWC2::Error::None,
2165 "[SF] Failed to set info (%d)",
2166 static_cast<int32_t>(error));
2167
2168 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2169 ALOGE_IF(error != HWC2::Error::None,
2170 "[SF] Failed to set transform %s: "
2171 "%s (%d)",
2172 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2173 static_cast<int32_t>(error));
2174 }
2175
2176 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2177 ALOGE_IF(error != HWC2::Error::None,
2178 "[SF] Failed to set composition type: %s (%d)",
2179 to_string(error).c_str(), static_cast<int32_t>(error));
2180
2181 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2182 ALOGE_IF(error != HWC2::Error::None,
2183 "[SF] Failed to set dataspace: %s (%d)",
2184 to_string(error).c_str(), static_cast<int32_t>(error));
2185
2186 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2187 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2188 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2189 "[SF] Failed to set hdrMetadata: %s (%d)",
2190 to_string(error).c_str(), static_cast<int32_t>(error));
2191
2192 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2193 ALOGE_IF(error != HWC2::Error::None,
2194 "[SF] Failed to set color: %s (%d)",
2195 to_string(error).c_str(), static_cast<int32_t>(error));
2196
2197 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2198 ALOGE_IF(error != HWC2::Error::None,
2199 "[SF] Failed to set visible region: %s (%d)",
2200 to_string(error).c_str(), static_cast<int32_t>(error));
2201}
2202
2203void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2204{
2205 HWC2::Error error;
2206
2207 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2208 ALOGE_IF(error != HWC2::Error::None,
2209 "[SF] Failed to set surface damage: %s (%d)",
2210 to_string(error).c_str(), static_cast<int32_t>(error));
2211
2212 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2213 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2214 ALOGE_IF(error != HWC2::Error::None,
2215 "[SF] Failed to set buffer: %s (%d)",
2216 to_string(error).c_str(), static_cast<int32_t>(error));
2217}
2218
2219void SurfaceFlinger::beginFrame()
2220{
Lloyd Piqueb7d12302018-07-26 12:56:47 -07002221 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
2222
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002223 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002224 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
2225 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2226 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07002227
2228 // If nothing has changed (!dirty), don't recompose.
2229 // If something changed, but we don't currently have any visible layers,
2230 // and didn't when we last did a composition, then skip it this time.
2231 // The second rule does two things:
2232 // - When all layers are removed from a display, we'll emit one black
2233 // frame, then nothing more until we get new layers.
2234 // - When a display is created with a private layer stack, we won't
2235 // emit any black frames until a layer is added to the layer stack.
2236 bool mustRecompose = dirty && !(empty && wasEmpty);
2237
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002238 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002239 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
2240 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07002241
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002242 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002243
2244 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002245 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07002246 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002247 }
David Sodman0756cdd2018-04-13 11:26:33 -07002248}
Jesse Hall028dc8f2013-08-20 16:35:32 -07002249
David Sodman0756cdd2018-04-13 11:26:33 -07002250void SurfaceFlinger::prepareFrame()
2251{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002252 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002253 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002254 continue;
2255 }
2256
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002257 status_t result = display->prepareFrame(*getBE().mHwc);
2258 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002259 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002260 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002261}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002262
David Sodman0756cdd2018-04-13 11:26:33 -07002263void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2264 ATRACE_CALL();
2265 ALOGV("setUpHWComposer");
2266
2267 switch (compositionInfo.compositionType)
2268 {
2269 case HWC2::Composition::Invalid:
2270 case HWC2::Composition::Client:
2271 break;
2272
2273 case HWC2::Composition::Sideband:
2274 configureSidebandComposition(compositionInfo);
2275 break;
2276
2277 case HWC2::Composition::SolidColor:
2278 configureHwcCommonData(compositionInfo);
2279 break;
2280
2281 case HWC2::Composition::Device:
2282 case HWC2::Composition::Cursor:
2283 configureHwcCommonData(compositionInfo);
2284 configureDeviceComposition(compositionInfo);
2285 break;
2286 }
2287}
2288
Mathias Agopiancd60f992012-08-16 16:28:27 -07002289void SurfaceFlinger::doComposition() {
2290 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002291 ALOGV("doComposition");
2292
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002293 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002294 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002295 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002296 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002297 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002298
2299 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002300 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002301
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002302 display->dirtyRegion.clear();
2303 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002304 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002305 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002306 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002307}
2308
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002309void SurfaceFlinger::postFramebuffer()
2310{
Mathias Agopian841cde52012-03-01 15:44:37 -08002311 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002312 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002313
Mathias Agopiana44b0412011-10-16 18:46:35 -07002314 const nsecs_t now = systemTime();
2315 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002316
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002317 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002318 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002319 continue;
2320 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002321 const auto displayId = display->getId();
2322 if (displayId >= 0) {
2323 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002324 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002325 display->onSwapBuffersCompleted();
2326 display->makeCurrent();
2327 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002328 sp<Fence> releaseFence = Fence::NO_FENCE;
2329
Chia-I Wu7b549592017-11-15 09:14:57 -08002330 // The layer buffer from the previous frame (if any) is released
2331 // by HWC only when the release fence from this frame (if any) is
2332 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002333 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002334 if (displayId >= 0) {
2335 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2336 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002337
2338 // If the layer was client composited in the previous frame, we
2339 // need to merge with the previous client target acquire fence.
2340 // Since we do not track that, always merge with the current
2341 // client target acquire fence when it is available, even though
2342 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002343 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002344 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002345 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002346 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002347
David Sodmanb8af7922017-12-21 15:17:55 -08002348 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002349 }
Chia-I Wu83806892017-11-16 10:50:20 -08002350
2351 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002352 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002353 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002354 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002355 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002356 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002357 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002358 }
2359 }
2360
Dominik Laskowski7e045462018-05-30 13:02:02 -07002361 if (displayId >= 0) {
2362 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002363 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002364 }
2365
Mathias Agopiana44b0412011-10-16 18:46:35 -07002366 mLastSwapBufferTime = systemTime() - now;
2367 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002368
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002369 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002370 const auto display = getDefaultDisplayDeviceLocked();
2371 if (display && getHwComposer().isConnected(display->getId())) {
2372 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002373 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2374 logFrameStats();
2375 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002376 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002377}
2378
Mathias Agopian87baae12012-07-31 12:38:26 -07002379void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002380{
Mathias Agopian841cde52012-03-01 15:44:37 -08002381 ATRACE_CALL();
2382
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002383 // here we keep a copy of the drawing state (that is the state that's
2384 // going to be overwritten by handleTransactionLocked()) outside of
2385 // mStateLock so that the side-effects of the State assignment
2386 // don't happen with mStateLock held (which can cause deadlocks).
2387 State drawingState(mDrawingState);
2388
Mathias Agopianca4d3602011-05-19 15:38:14 -07002389 Mutex::Autolock _l(mStateLock);
2390 const nsecs_t now = systemTime();
2391 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392
Mathias Agopianca4d3602011-05-19 15:38:14 -07002393 // Here we're guaranteed that some transaction flags are set
2394 // so we can call handleTransactionLocked() unconditionally.
2395 // We call getTransactionFlags(), which will also clear the flags,
2396 // with mStateLock held to guarantee that mCurrentState won't change
2397 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002398
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002399 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002400 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002401 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002402
Mathias Agopianca4d3602011-05-19 15:38:14 -07002403 mLastTransactionTime = systemTime() - now;
2404 mDebugInTransaction = 0;
2405 invalidateHwcGeometry();
2406 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002407}
2408
Dominik Laskowski7e045462018-05-30 13:02:02 -07002409DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002410 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002411 // Figure out whether the event is for the primary display or an
2412 // external display by matching the Hwc display id against one for a
2413 // connected display. If we did not find a match, we then check what
2414 // displays are not already connected to determine the type. If we don't
2415 // have a connected primary display, we assume the new display is meant to
2416 // be the primary display, and then if we don't have an external display,
2417 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002418 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2419 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002420 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002421 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002422 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002423 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002424 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002425 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002426 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002427 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002428 return DisplayDevice::DISPLAY_EXTERNAL;
2429 }
2430
2431 return DisplayDevice::DISPLAY_ID_INVALID;
2432}
2433
Lloyd Piqueba04e622017-12-14 17:11:26 -08002434void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2435 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002436 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002437 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002438 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002439 continue;
2440 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002441
2442 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2443 ALOGE("External displays are not supported by the vr hardware composer.");
2444 continue;
2445 }
2446
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002447 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002448 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002449 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002450 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002451 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002452
2453 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002454 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002455 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002456 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002457 DisplayDeviceState info;
2458 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002459 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2460 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002461 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002462 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002463 mInterceptor->saveDisplayCreation(info);
2464 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002465 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002466 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002467
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002468 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002469 if (idx >= 0) {
2470 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002471 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002472 mCurrentState.displays.removeItemsAt(idx);
2473 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002474 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002475 }
2476
2477 processDisplayChangesLocked();
2478 }
2479
2480 mPendingHotplugEvents.clear();
2481}
2482
Lloyd Pique99d3da52018-01-22 17:48:03 -08002483sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002484 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002485 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002486 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002487 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002488 HdrCapabilities hdrCapabilities;
2489 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002490
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002491 if (hasWideColorDisplay && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002492 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002493 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002494 if (isWideColorMode(colorMode)) {
2495 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002496 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002497
Dominik Laskowski7e045462018-05-30 13:02:02 -07002498 std::vector<RenderIntent> renderIntents =
2499 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002500 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002501 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002502
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002503 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2504 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2505 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002506
2507 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2508 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2509
2510 /*
2511 * Create our display's surface
2512 */
2513 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2514 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002515 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002516 renderSurface->setNativeWindow(nativeWindow.get());
2517 const int displayWidth = renderSurface->queryWidth();
2518 const int displayHeight = renderSurface->queryHeight();
2519
2520 // Make sure that composition can never be stalled by a virtual display
2521 // consumer that isn't processing buffers fast enough. We have to do this
2522 // in two places:
2523 // * Here, in case the display is composed entirely by HWC.
2524 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2525 // window's swap interval in eglMakeCurrent, so they'll override the
2526 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002527 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002528 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2529 }
2530
2531 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002532 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002533
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002534 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002535 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2536 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2537 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002538 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002539
2540 if (maxFrameBufferAcquiredBuffers >= 3) {
2541 nativeWindowSurface->preallocateBuffers();
2542 }
2543
2544 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002545 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2546 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002547 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002548 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002549 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002550 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002551 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002552 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002553 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002554 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002555 display->setLayerStack(state.layerStack);
2556 display->setProjection(state.orientation, state.viewport, state.frame);
2557 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002558
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002559 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002560}
2561
Lloyd Pique347200f2017-12-14 17:00:15 -08002562void SurfaceFlinger::processDisplayChangesLocked() {
2563 // here we take advantage of Vector's copy-on-write semantics to
2564 // improve performance by skipping the transaction entirely when
2565 // know that the lists are identical
2566 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2567 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2568 if (!curr.isIdenticalTo(draw)) {
2569 mVisibleRegionsDirty = true;
2570 const size_t cc = curr.size();
2571 size_t dc = draw.size();
2572
2573 // find the displays that were removed
2574 // (ie: in drawing state but not in current state)
2575 // also handle displays that changed
2576 // (ie: displays that are in both lists)
2577 for (size_t i = 0; i < dc;) {
2578 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2579 if (j < 0) {
2580 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002581 // Call makeCurrent() on the primary display so we can
2582 // be sure that nothing associated with this display
2583 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002584 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2585 defaultDisplay->makeCurrent();
2586 }
2587 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2588 display->disconnect(getHwComposer());
2589 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002590 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2591 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2592 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2593 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2594 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002595 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002596 } else {
2597 // this display is in both lists. see if something changed.
2598 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002599 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002600 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2601 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2602 if (state_binder != draw_binder) {
2603 // changing the surface is like destroying and
2604 // recreating the DisplayDevice, so we just remove it
2605 // from the drawing state, so that it get re-added
2606 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002607 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2608 display->disconnect(getHwComposer());
2609 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002610 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002611 mDrawingState.displays.removeItemsAt(i);
2612 dc--;
2613 // at this point we must loop to the next item
2614 continue;
2615 }
2616
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002617 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002618 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002619 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002620 }
2621 if ((state.orientation != draw[i].orientation) ||
2622 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002623 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002624 }
2625 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002626 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002627 }
2628 }
2629 }
2630 ++i;
2631 }
2632
2633 // find displays that were added
2634 // (ie: in current state but not in drawing state)
2635 for (size_t i = 0; i < cc; i++) {
2636 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2637 const DisplayDeviceState& state(curr[i]);
2638
2639 sp<DisplaySurface> dispSurface;
2640 sp<IGraphicBufferProducer> producer;
2641 sp<IGraphicBufferProducer> bqProducer;
2642 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002643 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002644
Dominik Laskowski7e045462018-05-30 13:02:02 -07002645 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002646 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002647 // Virtual displays without a surface are dormant:
2648 // they have external state (layer stack, projection,
2649 // etc.) but no internal state (i.e. a DisplayDevice).
2650 if (state.surface != nullptr) {
2651 // Allow VR composer to use virtual displays.
2652 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2653 int width = 0;
2654 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2655 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2656 int height = 0;
2657 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2658 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2659 int intFormat = 0;
2660 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2661 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002662 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002663
Dominik Laskowski7e045462018-05-30 13:02:02 -07002664 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2665 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002666 }
2667
2668 // TODO: Plumb requested format back up to consumer
2669
2670 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002671 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002672 bqProducer, bqConsumer,
2673 state.displayName);
2674
2675 dispSurface = vds;
2676 producer = vds;
2677 }
2678 } else {
2679 ALOGE_IF(state.surface != nullptr,
2680 "adding a supported display, but rendering "
2681 "surface is provided (%p), ignoring it",
2682 state.surface.get());
2683
Dominik Laskowski7e045462018-05-30 13:02:02 -07002684 displayId = state.type;
2685 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002686 producer = bqProducer;
2687 }
2688
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002689 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002690 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002691 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002692 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002693 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002694 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002695 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2696 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2697 true);
2698 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2699 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2700 true);
2701 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002702 }
2703 }
2704 }
2705 }
2706 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002707
2708 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002709}
2710
Mathias Agopian87baae12012-07-31 12:38:26 -07002711void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002712{
Dan Stoza7dde5992015-05-22 09:51:44 -07002713 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002714 mCurrentState.traverseInZOrder([](Layer* layer) {
2715 layer->notifyAvailableFrames();
2716 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002717
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718 /*
2719 * Traversal of the children
2720 * (perform the transaction for each of them if needed)
2721 */
2722
Mathias Agopian3559b072012-08-15 13:46:03 -07002723 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002724 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002726 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002727
2728 const uint32_t flags = layer->doTransaction(0);
2729 if (flags & Layer::eVisibleRegion)
2730 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002731 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002732 }
2733
2734 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002735 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736 */
2737
Mathias Agopiane57f2922012-08-09 16:29:12 -07002738 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002739 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002740 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002741 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002743 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002744 // The transform hint might have changed for some layers
2745 // (either because a display has changed, or because a layer
2746 // as changed).
2747 //
2748 // Walk through all the layers in currentLayers,
2749 // and update their transform hint.
2750 //
2751 // If a layer is visible only on a single display, then that
2752 // display is used to calculate the hint, otherwise we use the
2753 // default display.
2754 //
2755 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2756 // the hint is set before we acquire a buffer from the surface texture.
2757 //
2758 // NOTE: layer transactions have taken place already, so we use their
2759 // drawing state. However, SurfaceFlinger's own transaction has not
2760 // happened yet, so we must use the current state layer list
2761 // (soon to become the drawing state list).
2762 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002763 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002764 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002765 bool first = true;
2766 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002767 // NOTE: we rely on the fact that layers are sorted by
2768 // layerStack first (so we don't have to traverse the list
2769 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002770 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002771 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002772 currentlayerStack = layerStack;
2773 // figure out if this layerstack is mirrored
2774 // (more than one display) if so, pick the default display,
2775 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002776 hintDisplay = nullptr;
2777 for (const auto& [token, display] : mDisplays) {
2778 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2779 if (hintDisplay) {
2780 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002781 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002782 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002783 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002784 }
2785 }
2786 }
2787 }
Chet Haase91d25932013-04-11 15:24:55 -07002788
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002789 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002790 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2791 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002792
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002793 // could be null when this layer is using a layerStack
2794 // that is not visible on any display. Also can occur at
2795 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002796 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002797 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002798
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002799 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002800 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002801 if (hintDisplay) {
2802 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002803 }
Robert Carr2047fae2016-11-28 14:09:09 -08002804
2805 first = false;
2806 });
Mathias Agopian84300952012-11-21 16:02:13 -08002807 }
2808
2809
Mathias Agopian3559b072012-08-15 13:46:03 -07002810 /*
2811 * Perform our own transaction if needed
2812 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002813
2814 if (mLayersAdded) {
2815 mLayersAdded = false;
2816 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002817 mVisibleRegionsDirty = true;
2818 }
2819
2820 // some layers might have been removed, so
2821 // we need to update the regions they're exposing.
2822 if (mLayersRemoved) {
2823 mLayersRemoved = false;
2824 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002825 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002826 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002827 // this layer is not visible anymore
2828 // TODO: we could traverse the tree from front to back and
2829 // compute the actual visible region
2830 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002831 Region visibleReg;
2832 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002833 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002834 }
Robert Carr2047fae2016-11-28 14:09:09 -08002835 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002836 }
2837
2838 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002839
2840 updateCursorAsync();
2841}
2842
2843void SurfaceFlinger::updateCursorAsync()
2844{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002845 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002846 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002847 continue;
2848 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002849
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002850 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2851 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002852 }
2853 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002854}
2855
2856void SurfaceFlinger::commitTransaction()
2857{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002858 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002859 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002860 for (const auto& l : mLayersPendingRemoval) {
2861 recordBufferingStats(l->getName().string(),
2862 l->getOccupancyHistory(true));
2863 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002864 }
2865 mLayersPendingRemoval.clear();
2866 }
2867
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002868 // If this transaction is part of a window animation then the next frame
2869 // we composite should be considered an animation as well.
2870 mAnimCompositionPending = mAnimTransactionPending;
2871
Mathias Agopian4fec8732012-06-29 14:12:52 -07002872 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002873 // clear the "changed" flags in current state
2874 mCurrentState.colorMatrixChanged = false;
2875
Robert Carr1f0a16a2016-10-24 16:27:39 -07002876 mDrawingState.traverseInZOrder([](Layer* layer) {
2877 layer->commitChildList();
2878 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002879 mTransactionPending = false;
2880 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002881 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882}
2883
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002884void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2885 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002886 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002887 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002888
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889 Region aboveOpaqueLayers;
2890 Region aboveCoveredLayers;
2891 Region dirty;
2892
Mathias Agopian87baae12012-07-31 12:38:26 -07002893 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894
Robert Carr2047fae2016-11-28 14:09:09 -08002895 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002897 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898
Jesse Hall01e29052013-02-19 16:13:35 -08002899 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002900 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002901 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002902 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002903
Mathias Agopianab028732010-03-16 16:41:46 -07002904 /*
2905 * opaqueRegion: area of a surface that is fully opaque.
2906 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002908
2909 /*
2910 * visibleRegion: area of a surface that is visible on screen
2911 * and not fully transparent. This is essentially the layer's
2912 * footprint minus the opaque regions above it.
2913 * Areas covered by a translucent surface are considered visible.
2914 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002915 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002916
2917 /*
2918 * coveredRegion: area of a surface that is covered by all
2919 * visible regions above it (which includes the translucent areas).
2920 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002921 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002922
Jesse Halla8026d22012-09-25 13:25:04 -07002923 /*
2924 * transparentRegion: area of a surface that is hinted to be completely
2925 * transparent. This is only used to tell when the layer has no visible
2926 * non-transparent regions and can be removed from the layer list. It
2927 * does not affect the visibleRegion of this layer or any layers
2928 * beneath it. The hint may not be correct if apps don't respect the
2929 * SurfaceView restrictions (which, sadly, some don't).
2930 */
2931 Region transparentRegion;
2932
Mathias Agopianab028732010-03-16 16:41:46 -07002933
2934 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002935 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002936 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002937 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002938 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002939 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002940 if (!visibleRegion.isEmpty()) {
2941 // Remove the transparent area from the visible region
2942 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002943 if (tr.preserveRects()) {
2944 // transform the transparent region
2945 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002946 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002947 // transformation too complex, can't do the
2948 // transparent region optimization.
2949 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002950 }
Mathias Agopianab028732010-03-16 16:41:46 -07002951 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002952
Mathias Agopianab028732010-03-16 16:41:46 -07002953 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002954 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002955 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002956 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2957 // the opaque region is the layer's footprint
2958 opaqueRegion = visibleRegion;
2959 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002960 }
2961 }
2962
Robert Carre5f4f692018-01-12 13:12:28 -08002963 if (visibleRegion.isEmpty()) {
2964 layer->clearVisibilityRegions();
2965 return;
2966 }
2967
Mathias Agopianab028732010-03-16 16:41:46 -07002968 // Clip the covered region to the visible region
2969 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2970
2971 // Update aboveCoveredLayers for next (lower) layer
2972 aboveCoveredLayers.orSelf(visibleRegion);
2973
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002974 // subtract the opaque region covered by the layers above us
2975 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002976
2977 // compute this layer's dirty region
2978 if (layer->contentDirty) {
2979 // we need to invalidate the whole region
2980 dirty = visibleRegion;
2981 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002982 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002983 layer->contentDirty = false;
2984 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002985 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002986 * the exposed region consists of two components:
2987 * 1) what's VISIBLE now and was COVERED before
2988 * 2) what's EXPOSED now less what was EXPOSED before
2989 *
2990 * note that (1) is conservative, we start with the whole
2991 * visible region but only keep what used to be covered by
2992 * something -- which mean it may have been exposed.
2993 *
2994 * (2) handles areas that were not covered by anything but got
2995 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002996 */
Mathias Agopianab028732010-03-16 16:41:46 -07002997 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002998 const Region oldVisibleRegion = layer->visibleRegion;
2999 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003000 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3001 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003002 }
3003 dirty.subtractSelf(aboveOpaqueLayers);
3004
3005 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003006 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003007
Mathias Agopianab028732010-03-16 16:41:46 -07003008 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003009 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003010
Jesse Halla8026d22012-09-25 13:25:04 -07003011 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003012 layer->setVisibleRegion(visibleRegion);
3013 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003014 layer->setVisibleNonTransparentRegion(
3015 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003016 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003017
Mathias Agopian87baae12012-07-31 12:38:26 -07003018 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003019}
3020
Chia-I Wuab0c3192017-08-01 11:29:00 -07003021void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003022 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003023 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3024 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003025 }
3026 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003027}
3028
Dan Stoza6b9454d2014-11-07 16:00:59 -08003029bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003030{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003031 ALOGV("handlePageFlip");
3032
Brian Andersond6927fb2016-07-23 23:37:30 -07003033 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003034
Mathias Agopian4fec8732012-06-29 14:12:52 -07003035 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003036 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003037 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003038
3039 // Store the set of layers that need updates. This set must not change as
3040 // buffers are being latched, as this could result in a deadlock.
3041 // Example: Two producers share the same command stream and:
3042 // 1.) Layer 0 is latched
3043 // 2.) Layer 0 gets a new frame
3044 // 2.) Layer 1 gets a new frame
3045 // 3.) Layer 1 is latched.
3046 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3047 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003048 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003049 if (layer->hasQueuedFrame()) {
3050 frameQueued = true;
3051 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003052 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003053 } else {
3054 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003055 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003056 } else {
3057 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003058 }
Robert Carr2047fae2016-11-28 14:09:09 -08003059 });
3060
Dan Stoza9e56aa02015-11-02 13:00:03 -08003061 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07003062 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07003063 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003064 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003065 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003066 newDataLatched = true;
3067 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003068 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003069
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003070 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003071
3072 // If we will need to wake up at some time in the future to deal with a
3073 // queued frame that shouldn't be displayed during this vsync period, wake
3074 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003075 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003076 signalLayerUpdate();
3077 }
3078
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003079 // enter boot animation on first buffer latch
3080 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3081 ALOGI("Enter boot animation");
3082 mBootStage = BootStage::BOOTANIMATION;
3083 }
3084
Dan Stoza6b9454d2014-11-07 16:00:59 -08003085 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003086 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087}
3088
Mathias Agopianad456f92011-01-13 17:53:01 -08003089void SurfaceFlinger::invalidateHwcGeometry()
3090{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003091 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003092}
3093
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003094void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3095 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003096 // We only need to actually compose the display if:
3097 // 1) It is being handled by hardware composer, which may need this to
3098 // keep its virtual display state machine in sync, or
3099 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003100 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003101 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003102 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003103 return;
3104 }
3105
Dan Stoza9e56aa02015-11-02 13:00:03 -08003106 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003107 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003108
3109 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003110 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111}
3112
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003113bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003114 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003115
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003116 const Region bounds(display->bounds());
3117 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003118 const auto displayId = display->getId();
3119 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003120 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003121
Chia-I Wu8e50e692018-05-04 10:12:37 -07003122 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003123 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003124
Dan Stoza9e56aa02015-11-02 13:00:03 -08003125 if (hasClientComposition) {
3126 ALOGV("hasClientComposition");
3127
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003128 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003129 if (display->hasWideColorGamut()) {
3130 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003131 }
3132 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003133 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003134 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003135
Dominik Laskowski7e045462018-05-30 13:02:02 -07003136 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003137 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3138 HWC2::Capability::SkipClientColorTransform);
3139
Chia-I Wud49d6692018-06-27 07:17:41 +08003140 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003141 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3142 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003143 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003144 }
3145
Chia-I Wud49d6692018-06-27 07:17:41 +08003146 // The current enhanced saturation matrix is designed to enhance Display P3,
3147 // thus we only apply this matrix when the render intent is not colorimetric
3148 // and the output color space is Display P3.
3149 needsEnhancedColorMatrix =
3150 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3151 outputDataspace == Dataspace::DISPLAY_P3);
3152 if (needsEnhancedColorMatrix) {
3153 colorMatrix *= mEnhancedSaturationMatrix;
3154 }
3155
3156 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003157
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003158 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003159 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003160 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003161 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003162
3163 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003164 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3165 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3166 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003167 }
3168 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003169 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003170
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003171 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003172 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003173 // when using overlays, we assume a fully transparent framebuffer
3174 // NOTE: we could reduce how much we need to clear, for instance
3175 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003176 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003177 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003178 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003179 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003180 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003181 // we're left with the letterbox region
3182 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003183 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003184
3185 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003186 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003187
Mathias Agopianb9494d52012-04-18 02:28:45 -07003188 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003189 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003190 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003191 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003192 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003193 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003194
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003195 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003196 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003197 // scissor on the main display. It should never be needed
3198 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003199 const Rect& bounds = display->getBounds();
3200 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07003201 if (scissor != bounds) {
3202 // scissor doesn't match the screen's dimensions, so we
3203 // need to clear everything outside of it and enable
3204 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003205
Mathias Agopianf45c5102012-10-24 16:29:17 -07003206 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003207 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003208 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003209 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003210 }
3211 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003212 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003213
Mathias Agopian85d751c2012-08-29 16:59:24 -07003214 /*
3215 * and then, render the layers targeted at the framebuffer
3216 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003217
Dan Stoza9e56aa02015-11-02 13:00:03 -08003218 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003219 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003220 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003221 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003222 const Region clip(bounds.intersect(
3223 displayTransform.transform(layer->visibleRegion)));
3224 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003225 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003226 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003227 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003228 case HWC2::Composition::Cursor:
3229 case HWC2::Composition::Device:
3230 case HWC2::Composition::Sideband:
3231 case HWC2::Composition::SolidColor: {
3232 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003233 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05303234 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3235 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003236 // never clear the very first layer since we're
3237 // guaranteed the FB is already cleared
3238 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003239 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003240 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003241 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003242 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003243 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003244 break;
3245 }
3246 default:
3247 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003248 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003249 } else {
3250 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003251 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003252 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003253 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003254
Chia-I Wud49d6692018-06-27 07:17:41 +08003255 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003256 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003257 }
3258
Mathias Agopianf45c5102012-10-24 16:29:17 -07003259 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003260 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003261 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003262}
3263
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003264void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3265 const Region& region) const {
3266 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003267 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003268 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003269}
3270
Dan Stoza7d89d062015-04-30 13:29:25 -07003271status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003272 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003273 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003274 const sp<Layer>& lbc,
3275 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003276{
Dan Stoza7d89d062015-04-30 13:29:25 -07003277 // add this layer to the current state list
3278 {
3279 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003280 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003281 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3282 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003283 return NO_MEMORY;
3284 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003285 if (parent == nullptr) {
3286 mCurrentState.layersSortedByZ.add(lbc);
3287 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003288 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003289 ALOGE("addClientLayer called with a removed parent");
3290 return NAME_NOT_FOUND;
3291 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003292 parent->addChild(lbc);
3293 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003294
Yiwei Zhang243b3782018-05-15 17:40:04 -07003295 if (gbc != nullptr) {
3296 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3297 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3298 mMaxGraphicBufferProducerListSize,
3299 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3300 mGraphicBufferProducerList.size(),
3301 mMaxGraphicBufferProducerListSize, mNumLayers);
3302 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003303 mLayersAdded = true;
3304 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003305 }
3306
Mathias Agopian96f08192010-06-02 23:28:45 -07003307 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003308 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003309
Dan Stoza7d89d062015-04-30 13:29:25 -07003310 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003311}
3312
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003313status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003314 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003315 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3316}
Robert Carr7f9b8992017-03-10 11:08:39 -08003317
chaviwca27f252018-02-06 16:46:39 -08003318status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3319 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003320 if (layer->isPendingRemoval()) {
3321 return NO_ERROR;
3322 }
3323
Robert Carr1f0a16a2016-10-24 16:27:39 -07003324 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003325 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003326 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003327 if (topLevelOnly) {
3328 return NO_ERROR;
3329 }
3330
Chia-I Wu98f1c102017-05-30 14:54:08 -07003331 sp<Layer> ancestor = p;
3332 while (ancestor->getParent() != nullptr) {
3333 ancestor = ancestor->getParent();
3334 }
3335 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3336 ALOGE("removeLayer called with a layer whose parent has been removed");
3337 return NAME_NOT_FOUND;
3338 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003339
3340 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003341 } else {
3342 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003343 }
3344
Robert Carr136e2f62017-02-08 17:54:29 -08003345 // As a matter of normal operation, the LayerCleaner will produce a second
3346 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3347 // so we will succeed in promoting it, but it's already been removed
3348 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3349 // otherwise something has gone wrong and we are leaking the layer.
3350 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003351 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3352 layer->getName().string(),
3353 (p != nullptr) ? p->getName().string() : "no-parent");
3354 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003355 } else if (index < 0) {
3356 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003357 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003358
Chia-I Wuc6657022017-08-15 11:18:17 -07003359 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003360 mLayersPendingRemoval.add(layer);
3361 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003362 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003363 setTransactionFlags(eTransactionNeeded);
3364 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003365}
3366
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003367uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003368 return android_atomic_release_load(&mTransactionFlags);
3369}
3370
Mathias Agopian3f844832013-08-07 21:24:32 -07003371uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003372 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3373}
3374
Mathias Agopian3f844832013-08-07 21:24:32 -07003375uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003376 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3377}
3378
3379uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3380 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003381 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003382 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003383 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003384 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003385 }
3386 return old;
3387}
3388
chaviwca27f252018-02-06 16:46:39 -08003389bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3390 for (const ComposerState& state : states) {
3391 // Here we need to check that the interface we're given is indeed
3392 // one of our own. A malicious client could give us a nullptr
3393 // IInterface, or one of its own or even one of our own but a
3394 // different type. All these situations would cause us to crash.
3395 if (state.client == nullptr) {
3396 return true;
3397 }
3398
3399 sp<IBinder> binder = IInterface::asBinder(state.client);
3400 if (binder == nullptr) {
3401 return true;
3402 }
3403
3404 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3405 return true;
3406 }
3407 }
3408 return false;
3409}
3410
Mathias Agopian8b33f032012-07-24 20:43:54 -07003411void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003412 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003413 const Vector<DisplayState>& displays,
3414 uint32_t flags)
3415{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003416 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003417 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003418 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003419
chaviwca27f252018-02-06 16:46:39 -08003420 if (containsAnyInvalidClientState(states)) {
3421 return;
3422 }
3423
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003424 if (flags & eAnimation) {
3425 // For window updates that are part of an animation we must wait for
3426 // previous animation "frames" to be handled.
3427 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003428 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003429 if (CC_UNLIKELY(err != NO_ERROR)) {
3430 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003431 // caller after a few seconds.
3432 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3433 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003434 mAnimTransactionPending = false;
3435 break;
3436 }
3437 }
3438 }
3439
chaviwca27f252018-02-06 16:46:39 -08003440 for (const DisplayState& display : displays) {
3441 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003442 }
3443
chaviwca27f252018-02-06 16:46:39 -08003444 for (const ComposerState& state : states) {
3445 transactionFlags |= setClientStateLocked(state);
3446 }
3447
3448 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3449 // as destroyed should only occur after setting all other states. This is to allow for a
3450 // child re-parent to happen before marking its original parent as destroyed (which would
3451 // then mark the child as destroyed).
3452 for (const ComposerState& state : states) {
3453 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003454 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003455
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003456 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3457 // anyway. This can be used as a flush mechanism for previous async transactions.
3458 // Empty animation transaction can be used to simulate back-pressure, so also force a
3459 // transaction for empty animation transactions.
3460 if (transactionFlags == 0 &&
3461 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003462 transactionFlags = eTransactionNeeded;
3463 }
3464
Mathias Agopian386aa982011-11-07 21:58:03 -08003465 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003466 if (mInterceptor->isEnabled()) {
3467 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003468 }
Irvel468051e2016-06-13 16:44:44 -07003469
Mathias Agopian386aa982011-11-07 21:58:03 -08003470 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003471 const auto start = (flags & eEarlyWakeup)
3472 ? VSyncModulator::TransactionStart::EARLY
3473 : VSyncModulator::TransactionStart::NORMAL;
3474 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003475
3476 // if this is a synchronous transaction, wait for it to take effect
3477 // before returning.
3478 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003479 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003480 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003481 if (flags & eAnimation) {
3482 mAnimTransactionPending = true;
3483 }
3484 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003485 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3486 if (CC_UNLIKELY(err != NO_ERROR)) {
3487 // just in case something goes wrong in SF, return to the
3488 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003489 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3490 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003491 break;
3492 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003493 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003494 }
3495}
3496
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003497uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3498 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3499 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003500
Mathias Agopiane57f2922012-08-09 16:29:12 -07003501 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003502 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3503
3504 const uint32_t what = s.what;
3505 if (what & DisplayState::eSurfaceChanged) {
3506 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3507 state.surface = s.surface;
3508 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003509 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003510 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003511 if (what & DisplayState::eLayerStackChanged) {
3512 if (state.layerStack != s.layerStack) {
3513 state.layerStack = s.layerStack;
3514 flags |= eDisplayTransactionNeeded;
3515 }
3516 }
3517 if (what & DisplayState::eDisplayProjectionChanged) {
3518 if (state.orientation != s.orientation) {
3519 state.orientation = s.orientation;
3520 flags |= eDisplayTransactionNeeded;
3521 }
3522 if (state.frame != s.frame) {
3523 state.frame = s.frame;
3524 flags |= eDisplayTransactionNeeded;
3525 }
3526 if (state.viewport != s.viewport) {
3527 state.viewport = s.viewport;
3528 flags |= eDisplayTransactionNeeded;
3529 }
3530 }
3531 if (what & DisplayState::eDisplaySizeChanged) {
3532 if (state.width != s.width) {
3533 state.width = s.width;
3534 flags |= eDisplayTransactionNeeded;
3535 }
3536 if (state.height != s.height) {
3537 state.height = s.height;
3538 flags |= eDisplayTransactionNeeded;
3539 }
3540 }
3541
Mathias Agopiane57f2922012-08-09 16:29:12 -07003542 return flags;
3543}
3544
Robert Carrd4ae7f32018-06-07 16:10:57 -07003545bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3546 IPCThreadState* ipc = IPCThreadState::self();
3547 const int pid = ipc->getCallingPid();
3548 const int uid = ipc->getCallingUid();
3549
3550 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3551 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3552 return false;
3553 }
3554 return true;
3555}
3556
chaviwca27f252018-02-06 16:46:39 -08003557uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3558 const layer_state_t& s = composerState.state;
3559 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3560
Mathias Agopian13127d82013-03-05 17:47:11 -08003561 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003562 if (layer == nullptr) {
3563 return 0;
3564 }
3565
3566 if (layer->isPendingRemoval()) {
3567 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3568 return 0;
3569 }
3570
3571 uint32_t flags = 0;
3572
3573 const uint32_t what = s.what;
3574 bool geometryAppliesWithResize =
3575 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003576
3577 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3578 // pending state will also be deferred.
3579 if (what & layer_state_t::eDeferTransaction) {
3580 layer->pushPendingState();
3581 }
3582
chaviw8b3871a2017-11-01 17:41:01 -07003583 if (what & layer_state_t::ePositionChanged) {
3584 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3585 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003586 }
chaviw8b3871a2017-11-01 17:41:01 -07003587 }
3588 if (what & layer_state_t::eLayerChanged) {
3589 // NOTE: index needs to be calculated before we update the state
3590 const auto& p = layer->getParent();
3591 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003592 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003593 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003594 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 }
chaviw8b3871a2017-11-01 17:41:01 -07003600 } else {
3601 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003602 flags |= eTransactionNeeded|eTraversalNeeded;
3603 }
3604 }
chaviw8b3871a2017-11-01 17:41:01 -07003605 }
3606 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003607 // NOTE: index needs to be calculated before we update the state
3608 const auto& p = layer->getParent();
3609 if (p == nullptr) {
3610 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3611 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3612 mCurrentState.layersSortedByZ.removeAt(idx);
3613 mCurrentState.layersSortedByZ.add(layer);
3614 // we need traversal (state changed)
3615 // AND transaction (list changed)
3616 flags |= eTransactionNeeded|eTraversalNeeded;
3617 }
3618 } else {
3619 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3620 flags |= eTransactionNeeded|eTraversalNeeded;
3621 }
chaviw8b3871a2017-11-01 17:41:01 -07003622 }
3623 }
3624 if (what & layer_state_t::eSizeChanged) {
3625 if (layer->setSize(s.w, s.h)) {
3626 flags |= eTraversalNeeded;
3627 }
3628 }
3629 if (what & layer_state_t::eAlphaChanged) {
3630 if (layer->setAlpha(s.alpha))
3631 flags |= eTraversalNeeded;
3632 }
3633 if (what & layer_state_t::eColorChanged) {
3634 if (layer->setColor(s.color))
3635 flags |= eTraversalNeeded;
3636 }
3637 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003638 // TODO: b/109894387
3639 //
3640 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3641 // rotation. To see the problem observe that if we have a square parent, and a child
3642 // of the same size, then we rotate the child 45 degrees around it's center, the child
3643 // must now be cropped to a non rectangular 8 sided region.
3644 //
3645 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3646 // private API, and the WindowManager only uses rotation in one case, which is on a top
3647 // level layer in which cropping is not an issue.
3648 //
3649 // However given that abuse of rotation matrices could lead to surfaces extending outside
3650 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3651 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3652 // transformations.
3653 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003654 flags |= eTraversalNeeded;
3655 }
3656 if (what & layer_state_t::eTransparentRegionChanged) {
3657 if (layer->setTransparentRegionHint(s.transparentRegion))
3658 flags |= eTraversalNeeded;
3659 }
3660 if (what & layer_state_t::eFlagsChanged) {
3661 if (layer->setFlags(s.flags, s.mask))
3662 flags |= eTraversalNeeded;
3663 }
3664 if (what & layer_state_t::eCropChanged) {
3665 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3666 flags |= eTraversalNeeded;
3667 }
3668 if (what & layer_state_t::eFinalCropChanged) {
3669 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3670 flags |= eTraversalNeeded;
3671 }
3672 if (what & layer_state_t::eLayerStackChanged) {
3673 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3674 // We only allow setting layer stacks for top level layers,
3675 // everything else inherits layer stack from its parent.
3676 if (layer->hasParent()) {
3677 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3678 layer->getName().string());
3679 } else if (idx < 0) {
3680 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3681 "that also does not appear in the top level layer list. Something"
3682 " has gone wrong.", layer->getName().string());
3683 } else if (layer->setLayerStack(s.layerStack)) {
3684 mCurrentState.layersSortedByZ.removeAt(idx);
3685 mCurrentState.layersSortedByZ.add(layer);
3686 // we need traversal (state changed)
3687 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003688 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003689 }
3690 }
3691 if (what & layer_state_t::eDeferTransaction) {
3692 if (s.barrierHandle != nullptr) {
3693 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3694 } else if (s.barrierGbp != nullptr) {
3695 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3696 if (authenticateSurfaceTextureLocked(gbp)) {
3697 const auto& otherLayer =
3698 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3699 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3700 } else {
3701 ALOGE("Attempt to defer transaction to to an"
3702 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003703 }
3704 }
chaviw8b3871a2017-11-01 17:41:01 -07003705 // We don't trigger a traversal here because if no other state is
3706 // changed, we don't want this to cause any more work
3707 }
3708 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003709 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003710 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003711 if (!hadParent) {
3712 mCurrentState.layersSortedByZ.remove(layer);
3713 }
chaviw8b3871a2017-11-01 17:41:01 -07003714 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003715 }
chaviw8b3871a2017-11-01 17:41:01 -07003716 }
3717 if (what & layer_state_t::eReparentChildren) {
3718 if (layer->reparentChildren(s.reparentHandle)) {
3719 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003720 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003721 }
chaviw8b3871a2017-11-01 17:41:01 -07003722 if (what & layer_state_t::eDetachChildren) {
3723 layer->detachChildren();
3724 }
3725 if (what & layer_state_t::eOverrideScalingModeChanged) {
3726 layer->setOverrideScalingMode(s.overrideScalingMode);
3727 // We don't trigger a traversal here because if no other state is
3728 // changed, we don't want this to cause any more work
3729 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003730 return flags;
3731}
3732
chaviwca27f252018-02-06 16:46:39 -08003733void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3734 const layer_state_t& state = composerState.state;
3735 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3736
3737 sp<Layer> layer(client->getLayerUser(state.surface));
3738 if (layer == nullptr) {
3739 return;
3740 }
3741
3742 if (layer->isPendingRemoval()) {
3743 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3744 return;
3745 }
3746
3747 if (state.what & layer_state_t::eDestroySurface) {
3748 removeLayerLocked(mStateLock, layer);
3749 }
3750}
3751
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003752status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003753 const String8& name,
3754 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003755 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003756 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003757 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003758{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003759 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003760 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003761 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003762 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003763 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003764
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003765 status_t result = NO_ERROR;
3766
3767 sp<Layer> layer;
3768
Cody Northropbc755282017-03-31 12:00:08 -06003769 String8 uniqueName = getUniqueLayerName(name);
3770
Mathias Agopian3165cc22012-08-08 19:42:09 -07003771 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3772 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003773 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003774 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003775 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003776
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003777 break;
chaviw13fdc492017-06-27 12:40:18 -07003778 case ISurfaceComposerClient::eFXSurfaceColor:
3779 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003780 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003781 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003782 break;
3783 default:
3784 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003785 break;
3786 }
3787
Dan Stoza7d89d062015-04-30 13:29:25 -07003788 if (result != NO_ERROR) {
3789 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003790 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003791
Chia-I Wuab0c3192017-08-01 11:29:00 -07003792 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3793 // TODO b/64227542
3794 if (windowType == 441731) {
3795 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3796 layer->setPrimaryDisplayOnly();
3797 }
3798
Albert Chaulk479c60c2017-01-27 14:21:34 -05003799 layer->setInfo(windowType, ownerUid);
3800
Robert Carr1f0a16a2016-10-24 16:27:39 -07003801 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003802 if (result != NO_ERROR) {
3803 return result;
3804 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003805 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003806
3807 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003808 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003809}
3810
Cody Northropbc755282017-03-31 12:00:08 -06003811String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3812{
3813 bool matchFound = true;
3814 uint32_t dupeCounter = 0;
3815
3816 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3817 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3818
Dan Stoza436ccf32018-06-21 12:10:12 -07003819 // Grab the state lock since we're accessing mCurrentState
3820 Mutex::Autolock lock(mStateLock);
3821
Cody Northropbc755282017-03-31 12:00:08 -06003822 // Loop over layers until we're sure there is no matching name
3823 while (matchFound) {
3824 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003825 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003826 if (layer->getName() == uniqueName) {
3827 matchFound = true;
3828 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3829 }
3830 });
3831 }
3832
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003833 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3834 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003835
3836 return uniqueName;
3837}
3838
David Sodman0c69cad2017-08-21 12:12:51 -07003839status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003840 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3841 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003842{
3843 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003844 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003845 case PIXEL_FORMAT_TRANSPARENT:
3846 case PIXEL_FORMAT_TRANSLUCENT:
3847 format = PIXEL_FORMAT_RGBA_8888;
3848 break;
3849 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003850 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003851 break;
3852 }
3853
David Sodman0c69cad2017-08-21 12:12:51 -07003854 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3855 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003856 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003857 *handle = layer->getHandle();
3858 *gbp = layer->getProducer();
3859 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003860 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003861
David Sodman0c69cad2017-08-21 12:12:51 -07003862 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003863 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003864}
3865
chaviw13fdc492017-06-27 12:40:18 -07003866status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003867 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003868 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003869{
chaviw13fdc492017-06-27 12:40:18 -07003870 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003871 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003872 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003873}
3874
Mathias Agopianac9fa422013-02-11 16:40:36 -08003875status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003876{
Robert Carr9524cb32017-02-13 11:32:32 -08003877 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003878 status_t err = NO_ERROR;
3879 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003880 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003881 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003882 err = removeLayer(l);
3883 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3884 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003885 }
3886 return err;
3887}
3888
Mathias Agopian13127d82013-03-05 17:47:11 -08003889status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003890{
Mathias Agopian67106042013-03-14 19:18:13 -07003891 // called by ~LayerCleaner() when all references to the IBinder (handle)
3892 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003893 sp<Layer> l = layer.promote();
3894 if (l == nullptr) {
3895 // The layer has already been removed, carry on
3896 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003897 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003898 // If we have a parent, then we can continue to live as long as it does.
3899 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003900}
3901
Mathias Agopianb60314a2012-04-10 22:09:54 -07003902// ---------------------------------------------------------------------------
3903
Andy McFadden13a082e2012-08-24 10:16:42 -07003904void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003905 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3906 if (!displayToken) return;
3907
Jesse Hall01e29052013-02-19 16:13:35 -08003908 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003909 Vector<ComposerState> state;
3910 Vector<DisplayState> displays;
3911 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003912 d.what = DisplayState::eDisplayProjectionChanged |
3913 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003914 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003915 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003916 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003917 d.frame.makeInvalid();
3918 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003919 d.width = 0;
3920 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003921 displays.add(d);
3922 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003923
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003924 const auto display = getDisplayDevice(displayToken);
3925 if (!display) return;
3926
3927 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3928
3929 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003930 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003931 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003932
Brian Andersond0010582017-03-07 13:20:31 -08003933 // Use phase of 0 since phase is not known.
3934 // Use latency of 0, which will snap to the ideal latency.
3935 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003936}
3937
3938void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003939 // Async since we may be called from the main thread.
3940 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003941}
3942
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003943void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3944 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003945 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003946 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003947
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003948 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003949 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003950 return;
3951 }
3952
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003953 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003954 ALOGW("Trying to set power mode for virtual display");
3955 return;
3956 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003957
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003958 display->setPowerMode(mode);
3959
Lloyd Pique4dccc412018-01-22 17:21:36 -08003960 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003961 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003962 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003963 if (idx < 0) {
3964 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3965 return;
3966 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003967 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003968 }
3969
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003970 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003971 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003972 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003973 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003974 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003975 // FIXME: eventthread only knows about the main display right now
3976 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003977 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003978 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003979
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003980 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003981 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003982 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003983
3984 struct sched_param param = {0};
3985 param.sched_priority = 1;
3986 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3987 ALOGW("Couldn't set SCHED_FIFO on display on");
3988 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003989 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003990 // Turn off the display
3991 struct sched_param param = {0};
3992 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3993 ALOGW("Couldn't set SCHED_OTHER on display off");
3994 }
3995
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003996 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003997 disableHardwareVsync(true); // also cancels any in-progress resync
3998
Mathias Agopiancde87a32012-09-13 14:09:01 -07003999 // FIXME: eventthread only knows about the main display right now
4000 mEventThread->onScreenReleased();
4001 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004002
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004003 getHwComposer().setPowerMode(type, mode);
4004 mVisibleRegionsDirty = true;
4005 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004006 } else if (mode == HWC_POWER_MODE_DOZE ||
4007 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004008 // Update display while dozing
4009 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004010 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004011 // FIXME: eventthread only knows about the main display right now
4012 mEventThread->onScreenAcquired();
4013 resyncToHardwareVsync(true);
4014 }
4015 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4016 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004017 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004018 disableHardwareVsync(true); // also cancels any in-progress resync
4019 // FIXME: eventthread only knows about the main display right now
4020 mEventThread->onScreenReleased();
4021 }
4022 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004023 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004024 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004025 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004026 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004027
4028 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004029}
4030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004031void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004032 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004033 const auto display = getDisplayDevice(displayToken);
4034 if (!display) {
4035 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4036 displayToken.get());
4037 } else if (display->isVirtual()) {
4038 ALOGW("Attempt to set power mode %d for virtual display", mode);
4039 } else {
4040 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004041 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004042 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004043}
4044
4045// ---------------------------------------------------------------------------
4046
Lloyd Pique755e3192018-01-31 16:46:15 -08004047status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4048 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004049 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004050
Mathias Agopianbd115332013-04-18 16:41:04 -07004051 IPCThreadState* ipc = IPCThreadState::self();
4052 const int pid = ipc->getCallingPid();
4053 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004054
Mathias Agopianbd115332013-04-18 16:41:04 -07004055 if ((uid != AID_SHELL) &&
4056 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004057 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004058 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004059 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004060 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004061 // (this would indicate SF is stuck, but we want to be able to
4062 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004063 status_t err = mStateLock.timedLock(s2ns(1));
4064 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004065 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004066 result.appendFormat(
4067 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4068 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004069 }
4070
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004071 bool dumpAll = true;
4072 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004073 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004074
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004075 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004076 if ((index < numArgs) &&
4077 (args[index] == String16("--list"))) {
4078 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004079 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004080 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004081 }
4082
4083 if ((index < numArgs) &&
4084 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004085 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004086 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004087 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004088 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004089
4090 if ((index < numArgs) &&
4091 (args[index] == String16("--latency-clear"))) {
4092 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004093 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004094 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004095 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004096
4097 if ((index < numArgs) &&
4098 (args[index] == String16("--dispsync"))) {
4099 index++;
4100 mPrimaryDispSync.dump(result);
4101 dumpAll = false;
4102 }
Dan Stozab90cf072015-03-05 11:05:59 -08004103
4104 if ((index < numArgs) &&
4105 (args[index] == String16("--static-screen"))) {
4106 index++;
4107 dumpStaticScreenStats(result);
4108 dumpAll = false;
4109 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004110
4111 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004112 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004113 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004114 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004115 dumpAll = false;
4116 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004117
4118 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4119 index++;
4120 dumpWideColorInfo(result);
4121 dumpAll = false;
4122 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004123
4124 if ((index < numArgs) &&
4125 (args[index] == String16("--enable-layer-stats"))) {
4126 index++;
4127 mLayerStats.enable();
4128 dumpAll = false;
4129 }
4130
4131 if ((index < numArgs) &&
4132 (args[index] == String16("--disable-layer-stats"))) {
4133 index++;
4134 mLayerStats.disable();
4135 dumpAll = false;
4136 }
4137
4138 if ((index < numArgs) &&
4139 (args[index] == String16("--clear-layer-stats"))) {
4140 index++;
4141 mLayerStats.clear();
4142 dumpAll = false;
4143 }
4144
4145 if ((index < numArgs) &&
4146 (args[index] == String16("--dump-layer-stats"))) {
4147 index++;
4148 mLayerStats.dump(result);
4149 dumpAll = false;
4150 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004151
4152 if ((index < numArgs) &&
4153 (args[index] == String16("--display-identification"))) {
4154 index++;
4155 dumpDisplayIdentificationData(result);
4156 dumpAll = false;
4157 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004158
4159 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4160 index++;
4161 mTimeStats.parseArgs(asProto, args, index, result);
4162 dumpAll = false;
4163 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004164 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004165
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004166 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004167 if (asProto) {
4168 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4169 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4170 } else {
4171 dumpAllLocked(args, index, result);
4172 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004173 }
4174
Mathias Agopian9795c422009-08-26 16:36:26 -07004175 if (locked) {
4176 mStateLock.unlock();
4177 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004178 }
4179 write(fd, result.string(), result.size());
4180 return NO_ERROR;
4181}
4182
Dan Stozac7014012014-02-14 15:03:43 -08004183void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4184 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004185{
Robert Carr2047fae2016-11-28 14:09:09 -08004186 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004187 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004188 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004189}
4190
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004191void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004192 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004193{
4194 String8 name;
4195 if (index < args.size()) {
4196 name = String8(args[index]);
4197 index++;
4198 }
4199
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004200 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4201 getHwComposer().isConnected(displayId)) {
4202 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4203 const nsecs_t period = activeConfig->getVsyncPeriod();
4204 result.appendFormat("%" PRId64 "\n", period);
4205 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004206
4207 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004208 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004209 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004210 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004211 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004212 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004213 }
Robert Carr2047fae2016-11-28 14:09:09 -08004214 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004215 }
4216}
4217
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004218void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004219 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004220{
4221 String8 name;
4222 if (index < args.size()) {
4223 name = String8(args[index]);
4224 index++;
4225 }
4226
Robert Carr2047fae2016-11-28 14:09:09 -08004227 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004228 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004229 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004230 }
Robert Carr2047fae2016-11-28 14:09:09 -08004231 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004232
Svetoslavd85084b2014-03-20 10:28:31 -07004233 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004234}
4235
Jamie Gennis6547ff42013-07-16 20:12:42 -07004236// This should only be called from the main thread. Otherwise it would need
4237// the lock and should use mCurrentState rather than mDrawingState.
4238void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004239 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004240 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004241 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004242
4243 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4244}
4245
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004246void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004247{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004248 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004249
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004250 if (isLayerTripleBufferingDisabled())
4251 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004252
4253 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004254 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004255 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004256 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004257 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4258 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004259 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004260}
4261
Dan Stozab90cf072015-03-05 11:05:59 -08004262void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4263{
4264 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004265 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4266 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004267 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004268 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004269 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4270 b + 1, bucketTimeSec, percent);
4271 }
David Sodman4a36e932017-11-07 14:29:47 -08004272 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004273 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004274 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004275 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004276 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004277}
4278
Dan Stozae77c7662016-05-13 11:37:28 -07004279void SurfaceFlinger::recordBufferingStats(const char* layerName,
4280 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004281 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4282 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004283 for (const auto& segment : history) {
4284 if (!segment.usedThirdBuffer) {
4285 stats.twoBufferTime += segment.totalTime;
4286 }
4287 if (segment.occupancyAverage < 1.0f) {
4288 stats.doubleBufferedTime += segment.totalTime;
4289 } else if (segment.occupancyAverage < 2.0f) {
4290 stats.tripleBufferedTime += segment.totalTime;
4291 }
4292 ++stats.numSegments;
4293 stats.totalTime += segment.totalTime;
4294 }
4295}
4296
Brian Andersond6927fb2016-07-23 23:37:30 -07004297void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4298 result.appendFormat("Layer frame timestamps:\n");
4299
4300 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4301 const size_t count = currentLayers.size();
4302 for (size_t i=0 ; i<count ; i++) {
4303 currentLayers[i]->dumpFrameEvents(result);
4304 }
4305}
4306
Dan Stozae77c7662016-05-13 11:37:28 -07004307void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4308 result.append("Buffering stats:\n");
4309 result.append(" [Layer name] <Active time> <Two buffer> "
4310 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004311 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004312 typedef std::tuple<std::string, float, float, float> BufferTuple;
4313 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004314 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004315 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004316 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004317 if (stats.numSegments == 0) {
4318 continue;
4319 }
4320 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4321 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4322 stats.totalTime;
4323 float doubleBufferRatio = static_cast<float>(
4324 stats.doubleBufferedTime) / stats.totalTime;
4325 float tripleBufferRatio = static_cast<float>(
4326 stats.tripleBufferedTime) / stats.totalTime;
4327 sorted.insert({activeTime, {name, twoBufferRatio,
4328 doubleBufferRatio, tripleBufferRatio}});
4329 }
4330 for (const auto& sortedPair : sorted) {
4331 float activeTime = sortedPair.first;
4332 const BufferTuple& values = sortedPair.second;
4333 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4334 std::get<0>(values).c_str(), activeTime,
4335 std::get<1>(values), std::get<2>(values),
4336 std::get<3>(values));
4337 }
4338 result.append("\n");
4339}
4340
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004341void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004342 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004343 const int32_t displayId = display->getId();
4344 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4345 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004346 continue;
4347 }
4348
Dominik Laskowski7e045462018-05-30 13:02:02 -07004349 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004350 uint8_t port;
4351 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004352 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004353 result.append("no identification data\n");
4354 continue;
4355 }
4356
4357 if (!isEdid(data)) {
4358 result.append("unknown identification data: ");
4359 for (uint8_t byte : data) {
4360 result.appendFormat("%x ", byte);
4361 }
4362 result.append("\n");
4363 continue;
4364 }
4365
4366 const auto edid = parseEdid(data);
4367 if (!edid) {
4368 result.append("invalid EDID: ");
4369 for (uint8_t byte : data) {
4370 result.appendFormat("%x ", byte);
4371 }
4372 result.append("\n");
4373 continue;
4374 }
4375
4376 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4377 result.append(edid->displayName.data(), edid->displayName.length());
4378 result.append("\"\n");
4379 }
4380 result.append("\n");
4381}
4382
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004383void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4384 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004385 result.appendFormat("DisplayColorSetting: %s\n",
4386 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004387
4388 // TODO: print out if wide-color mode is active or not
4389
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004390 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004391 const int32_t displayId = display->getId();
4392 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004393 continue;
4394 }
4395
Dominik Laskowski7e045462018-05-30 13:02:02 -07004396 result.appendFormat("Display %d color modes:\n", displayId);
4397 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004398 for (auto&& mode : modes) {
4399 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4400 }
4401
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004402 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004403 result.appendFormat(" Current color mode: %s (%d)\n",
4404 decodeColorMode(currentMode).c_str(), currentMode);
4405 }
4406 result.append("\n");
4407}
4408
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004409LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004410 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004411 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4412 const State& state = useDrawing ? mDrawingState : mCurrentState;
4413 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004414 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004415 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004416 });
4417
4418 return layersProto;
4419}
4420
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004421LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004422 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004423
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004424 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004425 resolution->set_w(display.getWidth());
4426 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004427
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004428 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4429 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4430 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004431
Dominik Laskowski7e045462018-05-30 13:02:02 -07004432 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004433 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004434 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004435 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004436 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004437 }
4438 });
4439
4440 return layersProto;
4441}
4442
Mathias Agopian74d211a2013-04-22 16:55:35 +02004443void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4444 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004445{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004446 bool colorize = false;
4447 if (index < args.size()
4448 && (args[index] == String16("--color"))) {
4449 colorize = true;
4450 index++;
4451 }
4452
4453 Colorizer colorizer(colorize);
4454
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004455 // figure out if we're stuck somewhere
4456 const nsecs_t now = systemTime();
4457 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4458 const nsecs_t inTransaction(mDebugInTransaction);
4459 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4460 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4461
4462 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004463 * Dump library configuration.
4464 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004465
4466 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004467 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004468 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004469 appendSfConfigString(result);
4470 appendUiConfigString(result);
4471 appendGuiConfigString(result);
4472 result.append("\n");
4473
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004474 result.append("\nDisplay identification data:\n");
4475 dumpDisplayIdentificationData(result);
4476
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004477 result.append("\nWide-Color information:\n");
4478 dumpWideColorInfo(result);
4479
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004480 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004481 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004482 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004483 result.append(SyncFeatures::getInstance().toString());
4484 result.append("\n");
4485
Andy McFadden41d67d72014-04-25 16:58:34 -07004486 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004487 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004488 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004489
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004490 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4491 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004492 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4493 getHwComposer().isConnected(displayId)) {
4494 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004495 result.appendFormat("Display %d: "
4496 "app phase %" PRId64 " ns, "
4497 "sf phase %" PRId64 " ns, "
4498 "early app phase %" PRId64 " ns, "
4499 "early sf phase %" PRId64 " ns, "
4500 "early app gl phase %" PRId64 " ns, "
4501 "early sf gl phase %" PRId64 " ns, "
4502 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4503 displayId,
4504 vsyncPhaseOffsetNs,
4505 sfVsyncPhaseOffsetNs,
4506 appEarlyOffset,
4507 sfEarlyOffset,
4508 appEarlyGlOffset,
4509 sfEarlyOffset,
4510 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004511 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004512 result.append("\n");
4513
Dan Stozab90cf072015-03-05 11:05:59 -08004514 // Dump static screen stats
4515 result.append("\n");
4516 dumpStaticScreenStats(result);
4517 result.append("\n");
4518
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004519 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4520
Dan Stozae77c7662016-05-13 11:37:28 -07004521 dumpBufferingStats(result);
4522
Andy McFadden4803b742012-09-24 19:07:20 -07004523 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004524 * Dump the visible layer list
4525 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004526 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004527 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004528 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4529 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004530 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004531
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004532 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004533 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004534 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004535 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004536
4537 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004538 * Dump Display state
4539 */
4540
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004541 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004542 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004543 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004544 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004545 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004546 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004547 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004548
4549 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004550 * Dump SurfaceFlinger global state
4551 */
4552
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004553 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004554 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004555 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004556
Mathias Agopian888c8222012-08-04 21:10:38 -07004557 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004558 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004559
David Sodmanbc815282017-11-05 18:57:52 -08004560 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004561
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004562 if (display) {
4563 display->undefinedRegion.dump(result, "undefinedRegion");
4564 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4565 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004566 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004567 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4568 " last transaction time : %f us\n"
4569 " transaction-flags : %08x\n"
4570 " gpu_to_cpu_unsupported : %d\n",
4571 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4572 mTransactionFlags, !mGpuToCpuSupported);
4573
4574 if (display) {
4575 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4576 result.appendFormat(" refresh-rate : %f fps\n"
4577 " x-dpi : %f\n"
4578 " y-dpi : %f\n",
4579 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4580 activeConfig->getDpiY());
4581 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004582
Mathias Agopian74d211a2013-04-22 16:55:35 +02004583 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004584 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004585
Mathias Agopian74d211a2013-04-22 16:55:35 +02004586 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004587 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004588
4589 /*
4590 * VSYNC state
4591 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004592 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004593 result.append("\n");
4594
4595 /*
4596 * HWC layer minidump
4597 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004598 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004599 const int32_t displayId = display->getId();
4600 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004601 continue;
4602 }
4603
Dominik Laskowski7e045462018-05-30 13:02:02 -07004604 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004605 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004606 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004607 result.append("\n");
4608 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004609
4610 /*
4611 * Dump HWComposer state
4612 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004613 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004614 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004615 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004616 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004617 result.appendFormat(" h/w composer %s\n",
4618 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004619 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004620
4621 /*
4622 * Dump gralloc state
4623 */
4624 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4625 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004626
4627 /*
4628 * Dump VrFlinger state if in use.
4629 */
4630 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4631 result.append("VrFlinger state:\n");
4632 result.append(mVrFlinger->Dump().c_str());
4633 result.append("\n");
4634 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004635}
4636
Dominik Laskowski7e045462018-05-30 13:02:02 -07004637const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004638 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004639 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004640 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004641 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004642 }
4643 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004644
4645 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4646 static const Vector<sp<Layer>> empty;
4647 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004648}
4649
Keun young Park63f165f2012-08-31 10:53:36 -07004650bool SurfaceFlinger::startDdmConnection()
4651{
4652 void* libddmconnection_dso =
4653 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4654 if (!libddmconnection_dso) {
4655 return false;
4656 }
4657 void (*DdmConnection_start)(const char* name);
4658 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004659 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004660 if (!DdmConnection_start) {
4661 dlclose(libddmconnection_dso);
4662 return false;
4663 }
4664 (*DdmConnection_start)(getServiceName());
4665 return true;
4666}
4667
Chia-I Wu28f320b2018-05-03 11:02:56 -07004668void SurfaceFlinger::updateColorMatrixLocked() {
4669 mat4 colorMatrix;
4670 if (mGlobalSaturationFactor != 1.0f) {
4671 // Rec.709 luma coefficients
4672 float3 luminance{0.213f, 0.715f, 0.072f};
4673 luminance *= 1.0f - mGlobalSaturationFactor;
4674 mat4 saturationMatrix = mat4(
4675 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4676 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4677 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4678 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4679 );
4680 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4681 } else {
4682 colorMatrix = mClientColorMatrix * mDaltonizer();
4683 }
4684
4685 if (mCurrentState.colorMatrix != colorMatrix) {
4686 mCurrentState.colorMatrix = colorMatrix;
4687 mCurrentState.colorMatrixChanged = true;
4688 setTransactionFlags(eTransactionNeeded);
4689 }
4690}
4691
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004692status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004693 switch (code) {
4694 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004695 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004696 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004697 case CLEAR_ANIMATION_FRAME_STATS:
4698 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004699 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004700 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004701 case ENABLE_VSYNC_INJECTIONS:
4702 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004703 {
4704 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004705 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4706 IPCThreadState* ipc = IPCThreadState::self();
4707 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4708 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004709 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004710 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004711 break;
4712 }
Robert Carr1db73f62016-12-21 12:58:51 -08004713 /*
4714 * Calling setTransactionState is safe, because you need to have been
4715 * granted a reference to Client* and Handle* to do anything with it.
4716 *
4717 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4718 */
4719 case SET_TRANSACTION_STATE:
4720 case CREATE_SCOPED_CONNECTION:
4721 {
4722 return OK;
4723 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004724 case CAPTURE_SCREEN:
4725 {
4726 // codes that require permission check
4727 IPCThreadState* ipc = IPCThreadState::self();
4728 const int pid = ipc->getCallingPid();
4729 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004730 if ((uid != AID_GRAPHICS) &&
4731 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004732 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004733 return PERMISSION_DENIED;
4734 }
4735 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004736 }
chaviwa76b2712017-09-20 12:02:26 -07004737 case CAPTURE_LAYERS: {
4738 IPCThreadState* ipc = IPCThreadState::self();
4739 const int pid = ipc->getCallingPid();
4740 const int uid = ipc->getCallingUid();
4741 if ((uid != AID_GRAPHICS) &&
4742 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4743 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4744 return PERMISSION_DENIED;
4745 }
4746 break;
4747 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004748 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004749 return OK;
4750}
4751
4752status_t SurfaceFlinger::onTransact(
4753 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4754{
4755 status_t credentialCheck = CheckTransactCodeCredentials(code);
4756 if (credentialCheck != OK) {
4757 return credentialCheck;
4758 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004759
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004760 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4761 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004762 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004763 IPCThreadState* ipc = IPCThreadState::self();
4764 const int uid = ipc->getCallingUid();
4765 if (CC_UNLIKELY(uid != AID_SYSTEM
4766 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004767 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004768 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004769 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004770 return PERMISSION_DENIED;
4771 }
4772 int n;
4773 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004774 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004775 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004776 return NO_ERROR;
4777 case 1002: // SHOW_UPDATES
4778 n = data.readInt32();
4779 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004780 invalidateHwcGeometry();
4781 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004782 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004783 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004784 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004785 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004786 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004787 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004788 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004789 setTransactionFlags(
4790 eTransactionNeeded|
4791 eDisplayTransactionNeeded|
4792 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004793 return NO_ERROR;
4794 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004795 case 1006:{ // send empty update
4796 signalRefresh();
4797 return NO_ERROR;
4798 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004799 case 1008: // toggle use of hw composer
4800 n = data.readInt32();
4801 mDebugDisableHWC = n ? 1 : 0;
4802 invalidateHwcGeometry();
4803 repaintEverything();
4804 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004805 case 1009: // toggle use of transform hint
4806 n = data.readInt32();
4807 mDebugDisableTransformHint = n ? 1 : 0;
4808 invalidateHwcGeometry();
4809 repaintEverything();
4810 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004811 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004812 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004813 reply->writeInt32(0);
4814 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004815 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004816 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004817 return NO_ERROR;
4818 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004819 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004820 if (!display) {
4821 return NAME_NOT_FOUND;
4822 }
4823
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004824 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004825 return NO_ERROR;
4826 }
4827 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004828 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004829 // daltonize
4830 n = data.readInt32();
4831 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004832 case 1:
4833 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4834 break;
4835 case 2:
4836 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4837 break;
4838 case 3:
4839 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4840 break;
4841 default:
4842 mDaltonizer.setType(ColorBlindnessType::None);
4843 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004844 }
4845 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004846 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004847 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004848 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004849 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004850
4851 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004852 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004853 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004854 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004855 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004856 // apply a color matrix
4857 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004858 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004859 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004860 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004861 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004862 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004863 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004864 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004865 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004866 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004867 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004868
4869 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4870 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004871 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004872 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4873 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4874 }
4875
Chia-I Wu28f320b2018-05-03 11:02:56 -07004876 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004877 return NO_ERROR;
4878 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004879 // This is an experimental interface
4880 // Needs to be shifted to proper binder interface when we productize
4881 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004882 n = data.readInt32();
4883 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004884 return NO_ERROR;
4885 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004886 case 1017: {
4887 n = data.readInt32();
4888 mForceFullDamage = static_cast<bool>(n);
4889 return NO_ERROR;
4890 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004891 case 1018: { // Modify Choreographer's phase offset
4892 n = data.readInt32();
4893 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4894 return NO_ERROR;
4895 }
4896 case 1019: { // Modify SurfaceFlinger's phase offset
4897 n = data.readInt32();
4898 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4899 return NO_ERROR;
4900 }
Irvel468051e2016-06-13 16:44:44 -07004901 case 1020: { // Layer updates interceptor
4902 n = data.readInt32();
4903 if (n) {
4904 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004905 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004906 }
4907 else{
4908 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004909 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004910 }
4911 return NO_ERROR;
4912 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004913 case 1021: { // Disable HWC virtual displays
4914 n = data.readInt32();
4915 mUseHwcVirtualDisplays = !n;
4916 return NO_ERROR;
4917 }
Romain Guy0147a172017-06-01 13:53:56 -07004918 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004919 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004920 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004921
Chia-I Wu28f320b2018-05-03 11:02:56 -07004922 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004923 return NO_ERROR;
4924 }
Romain Guy54f154a2017-10-24 21:40:32 +01004925 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004926 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004927 invalidateHwcGeometry();
4928 repaintEverything();
4929 return NO_ERROR;
4930 }
4931 case 1024: { // Is wide color gamut rendering/color management supported?
4932 reply->writeBool(hasWideColorDisplay);
4933 return NO_ERROR;
4934 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004935 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004936 n = data.readInt32();
4937 if (n) {
4938 ALOGV("LayerTracing enabled");
4939 mTracing.enable();
4940 doTracing("tracing.enable");
4941 reply->writeInt32(NO_ERROR);
4942 } else {
4943 ALOGV("LayerTracing disabled");
4944 status_t err = mTracing.disable();
4945 reply->writeInt32(err);
4946 }
4947 return NO_ERROR;
4948 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004949 case 1026: { // Get layer tracing status
4950 reply->writeBool(mTracing.isEnabled());
4951 return NO_ERROR;
4952 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004953 // Is a DisplayColorSetting supported?
4954 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004955 const auto display = getDefaultDisplayDevice();
4956 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004957 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004958 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004959
4960 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4961 switch (setting) {
4962 case DisplayColorSetting::MANAGED:
4963 reply->writeBool(hasWideColorDisplay);
4964 break;
4965 case DisplayColorSetting::UNMANAGED:
4966 reply->writeBool(true);
4967 break;
4968 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004969 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004970 break;
4971 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004972 reply->writeBool(
4973 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004974 break;
4975 }
4976 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004977 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004978 // Is VrFlinger active?
4979 case 1028: {
4980 Mutex::Autolock _l(mStateLock);
4981 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4982 return NO_ERROR;
4983 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004984 }
4985 }
4986 return err;
4987}
4988
Steven Thomas6d8110b2017-08-31 18:24:21 -07004989void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004990 android_atomic_or(1, &mRepaintEverything);
4991 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004992}
4993
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004994// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4995class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004996public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004997 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4998 ~WindowDisconnector() {
4999 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005000 }
5001
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005002private:
5003 ANativeWindow* mWindow;
5004 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005005};
5006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005007status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5008 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
5009 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
5010 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005011 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005012 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005013
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005014 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005015
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005016 const auto display = getDisplayDeviceLocked(displayToken);
5017 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005019 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07005020
5021 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005022 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005023 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005024}
5025
5026status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005027 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005028 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005029 ATRACE_CALL();
5030
5031 class LayerRenderArea : public RenderArea {
5032 public:
Robert Carr578038f2018-03-09 12:25:24 -08005033 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5034 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07005035 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005036 mLayer(layer),
5037 mCrop(crop),
5038 mFlinger(flinger),
5039 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005040 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005041 Rect getBounds() const override {
5042 const Layer::State& layerState(mLayer->getDrawingState());
5043 return Rect(layerState.active.w, layerState.active.h);
5044 }
5045 int getHeight() const override { return mLayer->getDrawingState().active.h; }
5046 int getWidth() const override { return mLayer->getDrawingState().active.w; }
5047 bool isSecure() const override { return false; }
5048 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005049 Rect getSourceCrop() const override {
5050 if (mCrop.isEmpty()) {
5051 return getBounds();
5052 } else {
5053 return mCrop;
5054 }
5055 }
Robert Carr578038f2018-03-09 12:25:24 -08005056 class ReparentForDrawing {
5057 public:
5058 const sp<Layer>& oldParent;
5059 const sp<Layer>& newParent;
5060
5061 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5062 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005063 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005064 }
Robert Carr15eae092018-03-23 13:43:53 -07005065 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005066 };
5067
5068 void render(std::function<void()> drawLayers) override {
5069 if (!mChildrenOnly) {
5070 mTransform = mLayer->getTransform().inverse();
5071 drawLayers();
5072 } else {
5073 Rect bounds = getBounds();
5074 screenshotParentLayer =
5075 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5076 bounds.getWidth(), bounds.getHeight(), 0);
5077
5078 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5079 drawLayers();
5080 }
5081 }
chaviwa76b2712017-09-20 12:02:26 -07005082
chaviwa76b2712017-09-20 12:02:26 -07005083 private:
chaviw7206d492017-11-10 16:16:12 -08005084 const sp<Layer> mLayer;
5085 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005086
5087 // In the "childrenOnly" case we reparent the children to a screenshot
5088 // layer which has no properties set and which does not draw.
5089 sp<ContainerLayer> screenshotParentLayer;
5090 Transform mTransform;
5091
5092 SurfaceFlinger* mFlinger;
5093 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005094 };
5095
5096 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5097 auto parent = layerHandle->owner.promote();
5098
chaviw7206d492017-11-10 16:16:12 -08005099 if (parent == nullptr || parent->isPendingRemoval()) {
5100 ALOGE("captureLayers called with a removed parent");
5101 return NAME_NOT_FOUND;
5102 }
5103
Robert Carr578038f2018-03-09 12:25:24 -08005104 const int uid = IPCThreadState::self()->getCallingUid();
5105 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5106 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5107 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5108 return PERMISSION_DENIED;
5109 }
5110
chaviw7206d492017-11-10 16:16:12 -08005111 Rect crop(sourceCrop);
5112 if (sourceCrop.width() <= 0) {
5113 crop.left = 0;
5114 crop.right = parent->getCurrentState().active.w;
5115 }
5116
5117 if (sourceCrop.height() <= 0) {
5118 crop.top = 0;
5119 crop.bottom = parent->getCurrentState().active.h;
5120 }
5121
5122 int32_t reqWidth = crop.width() * frameScale;
5123 int32_t reqHeight = crop.height() * frameScale;
5124
Robert Carr578038f2018-03-09 12:25:24 -08005125 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005126
Robert Carr578038f2018-03-09 12:25:24 -08005127 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005128 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5129 if (!layer->isVisible()) {
5130 return;
Robert Carr578038f2018-03-09 12:25:24 -08005131 } else if (childrenOnly && layer == parent.get()) {
5132 return;
chaviwa76b2712017-09-20 12:02:26 -07005133 }
5134 visitor(layer);
5135 });
5136 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005137 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005138}
5139
5140status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5141 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005142 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005143 bool useIdentityTransform) {
5144 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005145
Iris Chang7501ed62018-04-30 14:45:42 +08005146 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005147
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005148 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5149 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5150 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5151 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005152
5153 // This mutex protects syncFd and captureResult for communication of the return values from the
5154 // main thread back to this Binder thread
5155 std::mutex captureMutex;
5156 std::condition_variable captureCondition;
5157 std::unique_lock<std::mutex> captureLock(captureMutex);
5158 int syncFd = -1;
5159 std::optional<status_t> captureResult;
5160
Robert Carr03480e22018-01-04 16:02:06 -08005161 const int uid = IPCThreadState::self()->getCallingUid();
5162 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5163
Dominik Laskowski8c001672018-05-30 16:52:06 -07005164 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005165 // If there is a refresh pending, bug out early and tell the binder thread to try again
5166 // after the refresh.
5167 if (mRefreshPending) {
5168 ATRACE_NAME("Skipping screenshot for now");
5169 std::unique_lock<std::mutex> captureLock(captureMutex);
5170 captureResult = std::make_optional<status_t>(EAGAIN);
5171 captureCondition.notify_one();
5172 return;
5173 }
5174
5175 status_t result = NO_ERROR;
5176 int fd = -1;
5177 {
5178 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005179 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005180 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5181 useIdentityTransform, forSystem, &fd);
5182 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005183 }
5184
5185 {
5186 std::unique_lock<std::mutex> captureLock(captureMutex);
5187 syncFd = fd;
5188 captureResult = std::make_optional<status_t>(result);
5189 captureCondition.notify_one();
5190 }
5191 });
5192
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005193 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005194 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005195 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005196 while (*captureResult == EAGAIN) {
5197 captureResult.reset();
5198 result = postMessageAsync(message);
5199 if (result != NO_ERROR) {
5200 return result;
5201 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005202 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005203 }
5204 result = *captureResult;
5205 }
5206
5207 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005208 sync_wait(syncFd, -1);
5209 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005210 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005211
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005212 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005213}
5214
chaviwa76b2712017-09-20 12:02:26 -07005215void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5216 TraverseLayersFunction traverseLayers, bool yswap,
5217 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005218 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005219
Lloyd Pique144e1162017-12-20 16:44:52 -08005220 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005221
5222 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005223 const auto raWidth = renderArea.getWidth();
5224 const auto raHeight = renderArea.getHeight();
5225
5226 const auto reqWidth = renderArea.getReqWidth();
5227 const auto reqHeight = renderArea.getReqHeight();
5228 Rect sourceCrop = renderArea.getSourceCrop();
5229
Iris Chang7501ed62018-04-30 14:45:42 +08005230 bool filtering = false;
5231 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5232 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5233 static_cast<int32_t>(reqHeight) != raWidth;
5234 } else {
5235 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5236 static_cast<int32_t>(reqHeight) != raHeight;
5237 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005238
Dan Stozac1879002014-05-22 15:59:05 -07005239 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005240 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005241 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005242 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005243 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5244 Transform tr;
5245 uint32_t flags = 0x00;
5246 switch (mPrimaryDisplayOrientation) {
5247 case DisplayState::eOrientation90:
5248 flags = Transform::ROT_90;
5249 break;
5250 case DisplayState::eOrientation180:
5251 flags = Transform::ROT_180;
5252 break;
5253 case DisplayState::eOrientation270:
5254 flags = Transform::ROT_270;
5255 break;
5256 }
5257 tr.set(flags, raWidth, raHeight);
5258 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005259 }
5260
5261 // ensure that sourceCrop is inside screen
5262 if (sourceCrop.left < 0) {
5263 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5264 }
chaviwa76b2712017-09-20 12:02:26 -07005265 if (sourceCrop.right > raWidth) {
5266 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005267 }
5268 if (sourceCrop.top < 0) {
5269 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5270 }
chaviwa76b2712017-09-20 12:02:26 -07005271 if (sourceCrop.bottom > raHeight) {
5272 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005273 }
5274
Chia-I Wu36574d92018-05-16 10:54:36 -07005275 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5276 engine.setOutputDataSpace(Dataspace::SRGB);
5277 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005278
Mathias Agopian180f10d2013-04-10 22:55:41 -07005279 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005280 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005281
Iris Chang7501ed62018-04-30 14:45:42 +08005282 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5283 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5284 // convert hw orientation into flag presentation
5285 // here inverse transform needed
5286 uint8_t hw_rot_90 = 0x00;
5287 uint8_t hw_flip_hv = 0x00;
5288 switch (mPrimaryDisplayOrientation) {
5289 case DisplayState::eOrientation90:
5290 hw_rot_90 = Transform::ROT_90;
5291 hw_flip_hv = Transform::ROT_180;
5292 break;
5293 case DisplayState::eOrientation180:
5294 hw_flip_hv = Transform::ROT_180;
5295 break;
5296 case DisplayState::eOrientation270:
5297 hw_rot_90 = Transform::ROT_90;
5298 break;
5299 }
5300
5301 // transform flags operation
5302 // 1) flip H V if both have ROT_90 flag
5303 // 2) XOR these flags
5304 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5305 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5306 if (rotation_rot_90 & hw_rot_90) {
5307 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5308 }
5309 rotation = static_cast<Transform::orientation_flags>
5310 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5311 }
5312
Mathias Agopian180f10d2013-04-10 22:55:41 -07005313 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005314 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005315 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005316 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005317
chaviw50da5042018-04-09 13:49:37 -07005318 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005319 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005320 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005321
chaviwa76b2712017-09-20 12:02:26 -07005322 traverseLayers([&](Layer* layer) {
5323 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005324 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005325 if (filtering) layer->setFiltering(false);
5326 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005327}
5328
chaviwa76b2712017-09-20 12:02:26 -07005329status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5330 TraverseLayersFunction traverseLayers,
5331 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005332 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005333 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005334 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005335 ATRACE_CALL();
5336
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005337 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005338
5339 traverseLayers([&](Layer* layer) {
5340 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5341 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005342
Robert Carr03480e22018-01-04 16:02:06 -08005343 // We allow the system server to take screenshots of secure layers for
5344 // use in situations like the Screen-rotation animation and place
5345 // the impetus on WindowManager to not persist them.
5346 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005347 ALOGW("FB is protected: PERMISSION_DENIED");
5348 return PERMISSION_DENIED;
5349 }
5350
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005351 // this binds the given EGLImage as a framebuffer for the
5352 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005353 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005354 if (bufferBond.getStatus() != NO_ERROR) {
5355 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005356 return INVALID_OPERATION;
5357 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005358
Dan Stozaabcda352017-06-01 14:37:39 -07005359 // this will in fact render into our dequeued buffer
5360 // via an FBO, which means we didn't have to create
5361 // an EGLSurface and therefore we're not
5362 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005363 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005364
Dan Stozaabcda352017-06-01 14:37:39 -07005365 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005366 getRenderEngine().finish();
5367 *outSyncFd = -1;
5368
chaviwa76b2712017-09-20 12:02:26 -07005369 const auto reqWidth = renderArea.getReqWidth();
5370 const auto reqHeight = renderArea.getReqHeight();
5371
Dan Stozaabcda352017-06-01 14:37:39 -07005372 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5373 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005374 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005375 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005376 } else {
5377 base::unique_fd syncFd = getRenderEngine().flush();
5378 if (syncFd < 0) {
5379 getRenderEngine().finish();
5380 }
5381 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005382 }
5383
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005384 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005385}
5386
Mathias Agopiand5556842013-09-19 17:08:37 -07005387void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005388 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005389 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005390 for (size_t y = 0; y < h; y++) {
5391 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5392 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005393 if (p[x] != 0xFF000000) return;
5394 }
5395 }
chaviwa76b2712017-09-20 12:02:26 -07005396 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005397
Robert Carr2047fae2016-11-28 14:09:09 -08005398 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005399 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005400 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005401 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5402 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5403 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5404 static_cast<float>(state.color.a));
5405 i++;
5406 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005407 }
5408}
5409
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005410// ---------------------------------------------------------------------------
5411
Dan Stoza412903f2017-04-27 13:42:17 -07005412void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5413 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005414}
5415
Dan Stoza412903f2017-04-27 13:42:17 -07005416void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5417 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005418}
5419
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005420void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5421 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005422 const LayerVector::Visitor& visitor) {
5423 // We loop through the first level of layers without traversing,
5424 // as we need to interpret min/max layer Z in the top level Z space.
5425 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005426 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005427 continue;
5428 }
5429 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005430 // relative layers are traversed in Layer::traverseInZOrder
5431 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005432 continue;
5433 }
5434 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005435 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005436 return;
5437 }
chaviwa76b2712017-09-20 12:02:26 -07005438 if (!layer->isVisible()) {
5439 return;
5440 }
5441 visitor(layer);
5442 });
5443 }
5444}
5445
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005446}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005447
Mathias Agopian3f844832013-08-07 21:24:32 -07005448#if defined(__gl_h_)
5449#error "don't include gl/gl.h in this file"
5450#endif
5451
5452#if defined(__gl2_h_)
5453#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005454#endif