blob: 5acfe59c4e1ec1308141312f0b1b936fb1f931c0 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070080#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070085#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070086#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070087#include "Scheduler/EventControlThread.h"
88#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070089#include "Scheduler/InjectVSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070090
Mathias Agopianff2ed702013-09-01 21:36:12 -070091#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070092
David Sodman7e4ae112018-02-09 15:02:28 -080093#include "android-base/stringprintf.h"
94
Jiyong Park4b20c2e2017-01-14 19:45:11 +090095#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080096#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070097#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080098#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090099#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900100
chaviw1d044282017-09-27 12:19:28 -0700101#include <layerproto/LayerProtoParser.h>
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103#define DISPLAY_COUNT 1
104
Mathias Agopianfee2b462013-07-03 12:34:01 -0700105/*
106 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
107 * black pixels.
108 */
109#define DEBUG_SCREENSHOTS false
110
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800111namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700112
Jaesoo Lee43518572017-01-23 19:03:16 +0900113using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700115using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700116using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700117using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700118using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119
Steven Thomasb02664d2017-07-26 18:48:28 -0700120namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700121
122#pragma clang diagnostic push
123#pragma clang diagnostic error "-Wswitch-enum"
124
125bool isWideColorMode(const ColorMode colorMode) {
126 switch (colorMode) {
127 case ColorMode::DISPLAY_P3:
128 case ColorMode::ADOBE_RGB:
129 case ColorMode::DCI_P3:
130 case ColorMode::BT2020:
131 case ColorMode::BT2100_PQ:
132 case ColorMode::BT2100_HLG:
133 return true;
134 case ColorMode::NATIVE:
135 case ColorMode::STANDARD_BT601_625:
136 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
137 case ColorMode::STANDARD_BT601_525:
138 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
139 case ColorMode::STANDARD_BT709:
140 case ColorMode::SRGB:
141 return false;
142 }
143 return false;
144}
145
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700146ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
147 switch (rotation) {
148 case ISurfaceComposer::eRotateNone:
149 return ui::Transform::ROT_0;
150 case ISurfaceComposer::eRotate90:
151 return ui::Transform::ROT_90;
152 case ISurfaceComposer::eRotate180:
153 return ui::Transform::ROT_180;
154 case ISurfaceComposer::eRotate270:
155 return ui::Transform::ROT_270;
156 }
157 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
158 return ui::Transform::ROT_0;
159}
160
Peiyong Linfca547f2018-07-09 13:03:33 -0700161#pragma clang diagnostic pop
162
Steven Thomasb02664d2017-07-26 18:48:28 -0700163class ConditionalLock {
164public:
165 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
166 if (lock) {
167 mMutex.lock();
168 }
169 }
170 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
171private:
172 Mutex& mMutex;
173 bool mLocked;
174};
Peiyong Linfca547f2018-07-09 13:03:33 -0700175
Steven Thomasb02664d2017-07-26 18:48:28 -0700176} // namespace anonymous
177
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178// ---------------------------------------------------------------------------
179
Mathias Agopian99b49842011-06-27 16:05:52 -0700180const String16 sHardwareTest("android.permission.HARDWARE_TEST");
181const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
182const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
183const String16 sDump("android.permission.DUMP");
184
185// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800186int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
187int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700188int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700189bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800190uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800191bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800192bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800193int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800194// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600195bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Lin13effd12018-07-24 17:01:47 -0700196bool SurfaceFlinger::useColorManagement;
Mathias Agopian99b49842011-06-27 16:05:52 -0700197
Kalle Raitaa099a242017-01-11 11:17:29 -0800198
199std::string getHwcServiceName() {
200 char value[PROPERTY_VALUE_MAX] = {};
201 property_get("debug.sf.hwc_service_name", value, "default");
202 ALOGI("Using HWComposer service: '%s'", value);
203 return std::string(value);
204}
205
206bool useTrebleTestingOverride() {
207 char value[PROPERTY_VALUE_MAX] = {};
208 property_get("debug.sf.treble_testing_override", value, "false");
209 ALOGI("Treble testing override: '%s'", value);
210 return std::string(value) == "true";
211}
212
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800213std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
214 switch(displayColorSetting) {
215 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700216 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800217 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700218 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800219 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700220 return std::string("Enhanced");
221 default:
222 return std::string("Unknown ") +
223 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800225}
226
Lloyd Pique99d3da52018-01-22 17:48:03 -0800227NativeWindowSurface::~NativeWindowSurface() = default;
228
229namespace impl {
230
231class NativeWindowSurface final : public android::NativeWindowSurface {
232public:
233 static std::unique_ptr<android::NativeWindowSurface> create(
234 const sp<IGraphicBufferProducer>& producer) {
235 return std::make_unique<NativeWindowSurface>(producer);
236 }
237
238 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
239 : surface(new Surface(producer, false)) {}
240
241 ~NativeWindowSurface() override = default;
242
243private:
244 sp<ANativeWindow> getNativeWindow() const override { return surface; }
245
246 void preallocateBuffers() override { surface->allocateBuffers(); }
247
248 sp<Surface> surface;
249};
250
251} // namespace impl
252
David Sodmanbc815282017-11-05 18:57:52 -0800253SurfaceFlingerBE::SurfaceFlingerBE()
254 : mHwcServiceName(getHwcServiceName()),
255 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800256 mFrameBuckets(),
257 mTotalTime(0),
258 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800259 mComposerSequenceId(0) {
260}
261
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800262SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800263 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800264 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700265 mTransactionPending(false),
266 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700267 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700268 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700269 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800270 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700271 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800273 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800274 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800275 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700277 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700278 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700279 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700280 mDebugInTransaction(0),
281 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700282 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700283 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700284 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800285 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800286 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800287 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700288 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800289 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800290 mCreateBufferQueue(&BufferQueue::createBufferQueue),
291 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800292
293SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800294 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800295
296 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
297 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
298
299 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
300 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
301
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800302 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
303 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800304
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700305 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
306 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
307
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700308 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
309 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
310
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800311 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
312 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
313
Steven Thomas050b2c82017-03-06 11:45:16 -0800314 // Vr flinger is only enabled on Daydream ready devices.
315 useVrFlinger = getBool< ISurfaceFlingerConfigs,
316 &ISurfaceFlingerConfigs::useVrFlinger>(false);
317
Fabien Sanglard1971b632017-03-10 14:50:03 -0800318 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
319 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
320
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600321 hasWideColorDisplay =
322 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700323 useColorManagement =
324 getBool<V1_2::ISurfaceFlingerConfigs, &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600325
Iris Chang7501ed62018-04-30 14:45:42 +0800326 V1_1::DisplayOrientation primaryDisplayOrientation =
327 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
328 V1_1::DisplayOrientation::ORIENTATION_0);
329
330 switch (primaryDisplayOrientation) {
331 case V1_1::DisplayOrientation::ORIENTATION_90:
332 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
333 break;
334 case V1_1::DisplayOrientation::ORIENTATION_180:
335 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
336 break;
337 case V1_1::DisplayOrientation::ORIENTATION_270:
338 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
339 break;
340 default:
341 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
342 break;
343 }
344 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
345
Lloyd Pique41be5d22018-06-21 13:11:48 -0700346 // Note: We create a local temporary with the real DispSync implementation
347 // type temporarily so we can initialize it with the configured values,
348 // before storing it for more generic use using the interface type.
349 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
350 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
351 SurfaceFlinger::dispSyncPresentTimeOffset);
352 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 // debugging stuff...
355 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700356
Mathias Agopianb4b17302013-03-20 18:36:41 -0700357 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700358 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700359
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800360 property_get("debug.sf.showupdates", value, "0");
361 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700362
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700363 property_get("debug.sf.ddms", value, "0");
364 mDebugDDMS = atoi(value);
365 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700366 if (!startDdmConnection()) {
367 // start failed, and DDMS debugging not enabled
368 mDebugDDMS = 0;
369 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700370 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700371 ALOGI_IF(mDebugRegion, "showupdates enabled");
372 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700373
374 property_get("debug.sf.disable_backpressure", value, "0");
375 mPropagateBackpressure = !atoi(value);
376 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700377
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800378 property_get("debug.sf.enable_hwc_vds", value, "0");
379 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800380 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800381
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800382 property_get("ro.sf.disable_triple_buffer", value, "1");
383 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800384 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700385
Yiwei Zhang243b3782018-05-15 17:40:04 -0700386 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700387 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
388 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
389
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200390 property_get("debug.sf.early_phase_offset_ns", value, "-1");
391 const int earlySfOffsetNs = atoi(value);
392
393 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
394 const int earlyGlSfOffsetNs = atoi(value);
395
396 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
397 const int earlyAppOffsetNs = atoi(value);
398
399 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
400 const int earlyGlAppOffsetNs = atoi(value);
401
402 const VSyncModulator::Offsets earlyOffsets =
403 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
404 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
405 const VSyncModulator::Offsets earlyGlOffsets =
406 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
407 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
408 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
409 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700410
Romain Guy11d63f42017-07-20 12:47:14 -0700411 // We should be reading 'persist.sys.sf.color_saturation' here
412 // but since /data may be encrypted, we need to wait until after vold
413 // comes online to attempt to read the property. The property is
414 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800415
416 if (useTrebleTestingOverride()) {
417 // Without the override SurfaceFlinger cannot connect to HIDL
418 // services that are not listed in the manifests. Considered
419 // deriving the setting from the set service name, but it
420 // would be brittle if the name that's not 'default' is used
421 // for production purposes later on.
422 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
423 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426void SurfaceFlinger::onFirstRef()
427{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800428 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429}
430
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431SurfaceFlinger::~SurfaceFlinger()
432{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800433}
434
Dan Stozac7014012014-02-14 15:03:43 -0800435void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800436{
437 // the window manager died on us. prepare its eulogy.
438
Andy McFadden13a082e2012-08-24 10:16:42 -0700439 // restore initial conditions (default device unblank, etc)
440 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800441
442 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700443 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800444}
445
Robert Carr1db73f62016-12-21 12:58:51 -0800446static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700447 status_t err = client->initCheck();
448 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800449 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450 }
Robert Carr1db73f62016-12-21 12:58:51 -0800451 return nullptr;
452}
453
454sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
455 return initClient(new Client(this));
456}
457
458sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
459 const sp<IGraphicBufferProducer>& gbp) {
460 if (authenticateSurfaceTexture(gbp) == false) {
461 return nullptr;
462 }
463 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
464 if (layer == nullptr) {
465 return nullptr;
466 }
467
468 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800469}
470
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700471sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
472 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700473{
474 class DisplayToken : public BBinder {
475 sp<SurfaceFlinger> flinger;
476 virtual ~DisplayToken() {
477 // no more references, this display must be terminated
478 Mutex::Autolock _l(flinger->mStateLock);
479 flinger->mCurrentState.displays.removeItem(this);
480 flinger->setTransactionFlags(eDisplayTransactionNeeded);
481 }
482 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700483 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700484 : flinger(flinger) {
485 }
486 };
487
488 sp<BBinder> token = new DisplayToken(this);
489
490 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700491 DisplayDeviceState info;
492 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700493 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700494 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800496 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 return token;
498}
499
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700500void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700501 Mutex::Autolock _l(mStateLock);
502
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700503 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700505 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700506 return;
507 }
508
509 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700510 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700511 ALOGE("destroyDisplay called for non-virtual display");
512 return;
513 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700514 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700515 mCurrentState.displays.removeItemsAt(idx);
516 setTransactionFlags(eDisplayTransactionNeeded);
517}
518
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700520 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800522 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700523 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700524 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700525}
526
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800527void SurfaceFlinger::bootFinished()
528{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700529 if (mStartPropertySetThread->join() != NO_ERROR) {
530 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800531 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800532 const nsecs_t now = systemTime();
533 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000534 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535
536 // wait patiently for the window manager death
537 const String16 name("window");
538 sp<IBinder> window(defaultServiceManager()->getService(name));
539 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700540 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541 }
542
Steven Thomas050b2c82017-03-06 11:45:16 -0800543 if (mVrFlinger) {
544 mVrFlinger->OnBootFinished();
545 }
546
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700547 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700548 // formerly we would just kill the process, but we now ask it to exit so it
549 // can choose where to stop the animation.
550 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700551
552 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
553 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
554 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700555
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800556 postMessageAsync(new LambdaMessage([this] {
557 readPersistentProperties();
558 mBootStage = BootStage::FINISHED;
559 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800560}
561
Dan Stoza436ccf32018-06-21 12:10:12 -0700562uint32_t SurfaceFlinger::getNewTexture() {
563 {
564 std::lock_guard lock(mTexturePoolMutex);
565 if (!mTexturePool.empty()) {
566 uint32_t name = mTexturePool.back();
567 mTexturePool.pop_back();
568 ATRACE_INT("TexturePoolSize", mTexturePool.size());
569 return name;
570 }
571
572 // The pool was too small, so increase it for the future
573 ++mTexturePoolSize;
574 }
575
576 // The pool was empty, so we need to get a new texture name directly using a
577 // blocking call to the main thread
578 uint32_t name = 0;
579 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
580 return name;
581}
582
Mathias Agopian3f844832013-08-07 21:24:32 -0700583void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700584 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700585}
586
Wei Wangf9b05ee2017-07-19 20:59:39 -0700587// Do not call property_set on main thread which will be blocked by init
588// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700590 ALOGI( "SurfaceFlinger's main thread ready to run. "
591 "Initializing graphics H/W...");
592
Thierry Strudel2924d012017-08-14 15:19:37 -0700593 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900594
Steven Thomasb02664d2017-07-26 18:48:28 -0700595 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800596
Steven Thomasb02664d2017-07-26 18:48:28 -0700597 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800598 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700599 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
600 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800601 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700602 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800603 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800604 "appEventThread");
605 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700606 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800607 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800608
Lloyd Pique24b0a482018-03-09 18:52:26 -0800609 mSFEventThread =
610 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700611 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800612 [this](nsecs_t timestamp) {
613 mInterceptor->saveVSyncEvent(timestamp);
614 },
615 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800616 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200617 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800618
Steven Thomasb02664d2017-07-26 18:48:28 -0700619 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700620 int32_t renderEngineFeature = 0;
621 renderEngineFeature |= (useColorManagement ? RE::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Lloyd Pique144e1162017-12-20 16:44:52 -0800622 getBE().mRenderEngine =
Peiyong Lin13effd12018-07-24 17:01:47 -0700623 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888, renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800624 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700625
626 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
627 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800628 getBE().mHwc.reset(
629 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700630 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800631 // Process any initial hotplug and resulting display changes.
632 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700633 const auto display = getDefaultDisplayDeviceLocked();
634 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
635 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
636 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800637
Lloyd Piquefcd86612017-12-14 17:15:36 -0800638 // make the default display GLContext current so that we can create textures
639 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700640 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800641
Steven Thomas050b2c82017-03-06 11:45:16 -0800642 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700643 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700644 // This callback is called from the vr flinger dispatch thread. We
645 // need to call signalTransaction(), which requires holding
646 // mStateLock when we're not on the main thread. Acquiring
647 // mStateLock from the vr flinger dispatch thread might trigger a
648 // deadlock in surface flinger (see b/66916578), so post a message
649 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700650 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700651 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
652 mVrFlingerRequestsDisplay = requestDisplay;
653 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700654 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800655 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700656 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
657 getHwComposer()
658 .getHwcDisplayId(display->getId())
659 .value_or(0),
660 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800661 if (!mVrFlinger) {
662 ALOGE("Failed to start vrflinger");
663 }
664 }
665
Lloyd Pique379adc12018-01-22 17:31:47 -0800666 mEventControlThread = std::make_unique<impl::EventControlThread>(
667 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700668
Mathias Agopian92a979a2012-08-02 18:32:23 -0700669 // initialize our drawing state
670 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700671
Andy McFadden13a082e2012-08-24 10:16:42 -0700672 // set initial conditions (e.g. unblank default device)
673 initializeDisplays();
674
David Sodmanbc815282017-11-05 18:57:52 -0800675 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700676
Wei Wangf9b05ee2017-07-19 20:59:39 -0700677 // Inform native graphics APIs whether the present timestamp is supported:
678 if (getHwComposer().hasCapability(
679 HWC2::Capability::PresentFenceIsNotReliable)) {
680 mStartPropertySetThread = new StartPropertySetThread(false);
681 } else {
682 mStartPropertySetThread = new StartPropertySetThread(true);
683 }
684
685 if (mStartPropertySetThread->Start() != NO_ERROR) {
686 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800687 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800688
Chia-I Wud49d6692018-06-27 07:17:41 +0800689 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
690 // is used to saturate legacy sRGB content. However, to make sure the same color under
691 // Display P3 will be saturated to the same color, we intentionally break the API spec
692 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
693 // such saturation matrix on Display P3 is understood fully, the API should always return
694 // identify matrix.
695 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
696 Dataspace::SRGB_LINEAR);
697
698 // we will apply this on Display P3.
699 if (mEnhancedSaturationMatrix != mat4()) {
700 ColorSpace srgb(ColorSpace::sRGB());
701 ColorSpace displayP3(ColorSpace::DisplayP3());
702 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
703 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
704 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
705 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800706
Dan Stoza9e56aa02015-11-02 13:00:03 -0800707 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700708}
709
Romain Guy11d63f42017-07-20 12:47:14 -0700710void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700711 Mutex::Autolock _l(mStateLock);
712
Romain Guy11d63f42017-07-20 12:47:14 -0700713 char value[PROPERTY_VALUE_MAX];
714
715 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800716 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700717 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800718 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100719
720 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700721 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700722}
723
Mathias Agopiana67e4182012-06-19 17:26:12 -0700724void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800725 // Start boot animation service by setting a property mailbox
726 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700727 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800728 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700729 if (mStartPropertySetThread->join() != NO_ERROR) {
730 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800731 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700732}
733
Mathias Agopian875d8e12013-06-07 15:35:48 -0700734size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800735 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700736}
737
Mathias Agopian875d8e12013-06-07 15:35:48 -0700738size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800739 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700740}
741
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800742// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800743
Jamie Gennis582270d2011-08-17 18:19:00 -0700744bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800745 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800746 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800747 return authenticateSurfaceTextureLocked(bufferProducer);
748}
749
750bool SurfaceFlinger::authenticateSurfaceTextureLocked(
751 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800752 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800753 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800754}
755
Brian Anderson6b376712017-04-04 10:51:39 -0700756status_t SurfaceFlinger::getSupportedFrameTimestamps(
757 std::vector<FrameEvent>* outSupported) const {
758 *outSupported = {
759 FrameEvent::REQUESTED_PRESENT,
760 FrameEvent::ACQUIRE,
761 FrameEvent::LATCH,
762 FrameEvent::FIRST_REFRESH_START,
763 FrameEvent::LAST_REFRESH_START,
764 FrameEvent::GPU_COMPOSITION_DONE,
765 FrameEvent::DEQUEUE_READY,
766 FrameEvent::RELEASE,
767 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700768 ConditionalLock _l(mStateLock,
769 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700770 if (!getHwComposer().hasCapability(
771 HWC2::Capability::PresentFenceIsNotReliable)) {
772 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
773 }
774 return NO_ERROR;
775}
776
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700777status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
778 Vector<DisplayInfo>* configs) {
779 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700780 return BAD_VALUE;
781 }
782
Jesse Hall692c7232012-11-08 15:41:56 -0800783 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700784 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
785 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700786 type = i;
787 break;
788 }
789 }
790
791 if (type < 0) {
792 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700793 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700794
Mathias Agopian8b736f12012-08-13 17:54:26 -0700795 // TODO: Not sure if display density should handled by SF any longer
796 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700797 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700798 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700799 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800800 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700801 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700802 }
803 return density;
804 }
805 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700806 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700807 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700808 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700809 return getDensityFromProperty("ro.sf.lcd_density"); }
810 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700811
Dan Stoza7f7da322014-05-02 15:26:25 -0700812 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700813
Steven Thomas6d8110b2017-08-31 18:24:21 -0700814 ConditionalLock _l(mStateLock,
815 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800816 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700817 DisplayInfo info = DisplayInfo();
818
Dan Stoza9e56aa02015-11-02 13:00:03 -0800819 float xdpi = hwConfig->getDpiX();
820 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700821
822 if (type == DisplayDevice::DISPLAY_PRIMARY) {
823 // The density of the device is provided by a build property
824 float density = Density::getBuildDensity() / 160.0f;
825 if (density == 0) {
826 // the build doesn't provide a density -- this is wrong!
827 // use xdpi instead
828 ALOGE("ro.sf.lcd_density must be defined as a build property");
829 density = xdpi / 160.0f;
830 }
831 if (Density::getEmuDensity()) {
832 // if "qemu.sf.lcd_density" is specified, it overrides everything
833 xdpi = ydpi = density = Density::getEmuDensity();
834 density /= 160.0f;
835 }
836 info.density = density;
837
838 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700839 const auto display = getDefaultDisplayDeviceLocked();
840 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 } else {
842 // TODO: where should this value come from?
843 static const int TV_DENSITY = 213;
844 info.density = TV_DENSITY / 160.0f;
845 info.orientation = 0;
846 }
847
Dan Stoza9e56aa02015-11-02 13:00:03 -0800848 info.w = hwConfig->getWidth();
849 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700850 info.xdpi = xdpi;
851 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800852 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900853 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800854
Andy McFadden91b2ca82014-06-13 14:04:23 -0700855 // This is how far in advance a buffer must be queued for
856 // presentation at a given time. If you want a buffer to appear
857 // on the screen at time N, you must submit the buffer before
858 // (N - presentationDeadline).
859 //
860 // Normally it's one full refresh period (to give SF a chance to
861 // latch the buffer), but this can be reduced by configuring a
862 // DispSync offset. Any additional delays introduced by the hardware
863 // composer or panel must be accounted for here.
864 //
865 // We add an additional 1ms to allow for processing time and
866 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800867 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800868 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700869
870 // All non-virtual displays are currently considered secure.
871 info.secure = true;
872
Iris Chang7501ed62018-04-30 14:45:42 +0800873 if (type == DisplayDevice::DISPLAY_PRIMARY &&
874 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
875 std::swap(info.w, info.h);
876 }
877
Michael Wright28f24d02016-07-12 13:30:53 -0700878 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700879 }
880
Dan Stoza7f7da322014-05-02 15:26:25 -0700881 return NO_ERROR;
882}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700883
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700884status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
885 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700886 return BAD_VALUE;
887 }
888
889 // FIXME for now we always return stats for the primary display
890 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700891 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
892 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700893 return NO_ERROR;
894}
895
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -0700896status_t SurfaceFlinger::getDisplayViewport(const sp<IBinder>& display, Rect* outViewport) {
897 if (outViewport == nullptr || display.get() == nullptr) {
898 return BAD_VALUE;
899 }
900
901 sp<const DisplayDevice> device(getDisplayDevice(display));
902 if (device == nullptr) {
903 return BAD_VALUE;
904 }
905
906 *outViewport = device->getViewport();
907
908 return NO_ERROR;
909}
910
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700911int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
912 const auto display = getDisplayDevice(displayToken);
913 if (!display) {
914 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800915 return BAD_VALUE;
916 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700919}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700920
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700921void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
922 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700923 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700924 return;
925 }
926
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700927 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700928 ALOGW("Trying to set config for virtual display");
929 return;
930 }
931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932 display->setActiveConfig(mode);
933 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700934}
935
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700936status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700937 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938 Vector<DisplayInfo> configs;
939 getDisplayConfigs(displayToken, &configs);
940 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
941 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
942 configs.size());
943 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700944 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945 const auto display = getDisplayDevice(displayToken);
946 if (!display) {
947 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
948 displayToken.get());
949 } else if (display->isVirtual()) {
950 ALOGW("Attempt to set active config %d for virtual display", mode);
951 } else {
952 setActiveConfigInternal(display, mode);
953 }
954 }));
955
Mathias Agopian888c8222012-08-04 21:10:38 -0700956 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700957}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700958status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
959 Vector<ColorMode>* outColorModes) {
960 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700961 return BAD_VALUE;
962 }
963
Michael Wright28f24d02016-07-12 13:30:53 -0700964 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700965 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
966 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700967 type = i;
968 break;
969 }
970 }
971
972 if (type < 0) {
973 return type;
974 }
975
Peiyong Lina52f0292018-03-14 17:26:31 -0700976 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700977 {
978 ConditionalLock _l(mStateLock,
979 std::this_thread::get_id() != mMainThreadId);
980 modes = getHwComposer().getColorModes(type);
981 }
Michael Wright28f24d02016-07-12 13:30:53 -0700982 outColorModes->clear();
983 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
984
985 return NO_ERROR;
986}
987
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700988ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
989 if (const auto display = getDisplayDevice(displayToken)) {
990 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700991 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700992 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700993}
994
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700995void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
996 Dataspace dataSpace, RenderIntent renderIntent) {
997 ColorMode currentMode = display->getActiveColorMode();
998 Dataspace currentDataSpace = display->getCompositionDataSpace();
999 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001000
Peiyong Lin38e9a562018-04-10 16:24:20 -07001001 if (mode == currentMode && dataSpace == currentDataSpace &&
1002 renderIntent == currentRenderIntent) {
1003 return;
1004 }
1005
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001006 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001007 ALOGW("Trying to set config for virtual display");
1008 return;
1009 }
1010
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001011 display->setActiveColorMode(mode);
1012 display->setCompositionDataSpace(dataSpace);
1013 display->setActiveRenderIntent(renderIntent);
1014 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001015
1016 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001017 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1018 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001019}
1020
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001021status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001022 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001023 Vector<ColorMode> modes;
1024 getDisplayColorModes(displayToken, &modes);
1025 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1026 if (mode < ColorMode::NATIVE || !exists) {
1027 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1028 decodeColorMode(mode).c_str(), mode, displayToken.get());
1029 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001030 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031 const auto display = getDisplayDevice(displayToken);
1032 if (!display) {
1033 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1034 decodeColorMode(mode).c_str(), mode, displayToken.get());
1035 } else if (display->isVirtual()) {
1036 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1037 decodeColorMode(mode).c_str(), mode);
1038 } else {
1039 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1040 RenderIntent::COLORIMETRIC);
1041 }
1042 }));
1043
Michael Wright28f24d02016-07-12 13:30:53 -07001044 return NO_ERROR;
1045}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001046
Svetoslavd85084b2014-03-20 10:28:31 -07001047status_t SurfaceFlinger::clearAnimationFrameStats() {
1048 Mutex::Autolock _l(mStateLock);
1049 mAnimFrameTracker.clearStats();
1050 return NO_ERROR;
1051}
1052
1053status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1054 Mutex::Autolock _l(mStateLock);
1055 mAnimFrameTracker.getStats(outStats);
1056 return NO_ERROR;
1057}
1058
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001059status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1060 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001061 Mutex::Autolock _l(mStateLock);
1062
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001063 const auto display = getDisplayDeviceLocked(displayToken);
1064 if (!display) {
1065 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001066 return BAD_VALUE;
1067 }
1068
Peiyong Linfb069302018-04-25 14:34:31 -07001069 // At this point the DisplayDeivce should already be set up,
1070 // meaning the luminance information is already queried from
1071 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001072 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001073 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1074 capabilities.getDesiredMaxLuminance(),
1075 capabilities.getDesiredMaxAverageLuminance(),
1076 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001077
1078 return NO_ERROR;
1079}
1080
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001081status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001082 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001083 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001084
Chia-I Wu90f669f2017-10-05 14:24:41 -07001085 if (mInjectVSyncs == enable) {
1086 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001087 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001088
1089 if (enable) {
1090 ALOGV("VSync Injections enabled");
1091 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001092 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001093 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001094 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001095 impl::EventThread::InterceptVSyncsCallback(),
1096 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001097 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001098 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001099 } else {
1100 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001101 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001102 }
1103
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001104 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001105 }));
1106
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001107 return NO_ERROR;
1108}
1109
1110status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001111 Mutex::Autolock _l(mStateLock);
1112
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001113 if (!mInjectVSyncs) {
1114 ALOGE("VSync Injections not enabled");
1115 return BAD_VALUE;
1116 }
1117 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1118 ALOGV("Injecting VSync inside SurfaceFlinger");
1119 mVSyncInjector->onInjectSyncEvent(when);
1120 }
1121 return NO_ERROR;
1122}
1123
Lloyd Pique755e3192018-01-31 16:46:15 -08001124status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1125 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001126 // Try to acquire a lock for 1s, fail gracefully
1127 const status_t err = mStateLock.timedLock(s2ns(1));
1128 const bool locked = (err == NO_ERROR);
1129 if (!locked) {
1130 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1131 return TIMED_OUT;
1132 }
1133
1134 outLayers->clear();
1135 mCurrentState.traverseInZOrder([&](Layer* layer) {
1136 outLayers->push_back(layer->getLayerDebugInfo());
1137 });
1138
1139 mStateLock.unlock();
1140 return NO_ERROR;
1141}
1142
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001143// ----------------------------------------------------------------------------
1144
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001145sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1146 ISurfaceComposer::VsyncSource vsyncSource) {
1147 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1148 return mSFEventThread->createEventConnection();
1149 } else {
1150 return mEventThread->createEventConnection();
1151 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001152}
1153
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001154// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001155
1156void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001157 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001158}
1159
1160void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001161 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001162}
1163
1164void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001165 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001166}
1167
1168void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001169 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001170 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001171}
1172
1173status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001174 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001175 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001176}
1177
1178status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001179 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001180 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001181 if (res == NO_ERROR) {
1182 msg->wait();
1183 }
1184 return res;
1185}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001186
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001187void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001188 do {
1189 waitForEvent();
1190 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001191}
1192
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001193void SurfaceFlinger::enableHardwareVsync() {
1194 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001195 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001196 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001197 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001198 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001199 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001200}
1201
Jesse Hall948fe0c2013-10-14 12:56:09 -07001202void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001203 Mutex::Autolock _l(mHWVsyncLock);
1204
Jesse Hall948fe0c2013-10-14 12:56:09 -07001205 if (makeAvailable) {
1206 mHWVsyncAvailable = true;
1207 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001208 // Hardware vsync is not currently available, so abort the resync
1209 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001210 return;
1211 }
1212
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001213 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1214 if (!getHwComposer().isConnected(displayId)) {
1215 return;
1216 }
1217
1218 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001219 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001220
Lloyd Pique41be5d22018-06-21 13:11:48 -07001221 mPrimaryDispSync->reset();
1222 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223
1224 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001225 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001226 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001227 mPrimaryHWVsyncEnabled = true;
1228 }
1229}
1230
Jesse Hall948fe0c2013-10-14 12:56:09 -07001231void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001232 Mutex::Autolock _l(mHWVsyncLock);
1233 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001234 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001235 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001236 mPrimaryHWVsyncEnabled = false;
1237 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001238 if (makeUnavailable) {
1239 mHWVsyncAvailable = false;
1240 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001241}
1242
Tim Murray4a4e4a22016-04-19 16:29:23 +00001243void SurfaceFlinger::resyncWithRateLimit() {
1244 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001245
1246 // No explicit locking is needed here since EventThread holds a lock while calling this method
1247 static nsecs_t sLastResyncAttempted = 0;
1248 const nsecs_t now = systemTime();
1249 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001250 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001251 }
Dan Stoza57164302017-05-08 14:03:54 -07001252 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001253}
1254
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001255void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1256 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001257 ATRACE_NAME("SF onVsync");
1258
Steven Thomas3cfac282017-02-06 12:29:30 -08001259 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001260 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001261 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001262 return;
1263 }
1264
1265 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001266 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001267 return;
1268 }
1269
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001270 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1271 // For now, we don't do anything with external display vsyncs.
1272 return;
1273 }
1274
Jamie Gennisd1700752013-10-14 12:22:52 -07001275 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001276
Jamie Gennisd1700752013-10-14 12:22:52 -07001277 { // Scope for the lock
1278 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001279 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001280 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001281 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001282 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001283
1284 if (needsHwVsync) {
1285 enableHardwareVsync();
1286 } else {
1287 disableHardwareVsync(false);
1288 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001289}
1290
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001291void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001292 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1293 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001294}
1295
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001296void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001297 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001298 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001299 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001300
Lloyd Piqueba04e622017-12-14 17:11:26 -08001301 // Ignore events that do not have the right sequenceId.
1302 if (sequenceId != getBE().mComposerSequenceId) {
1303 return;
1304 }
1305
Steven Thomasb02664d2017-07-26 18:48:28 -07001306 // Only lock if we're not on the main thread. This function is normally
1307 // called on a hwbinder thread, but for the primary display it's called on
1308 // the main thread with the state lock already held, so don't attempt to
1309 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001310 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001311
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001312 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001313
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001314 if (std::this_thread::get_id() == mMainThreadId) {
1315 // Process all pending hot plug events immediately if we are on the main thread.
1316 processDisplayHotplugEventsLocked();
1317 }
1318
Lloyd Piqueba04e622017-12-14 17:11:26 -08001319 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001320}
1321
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001322void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001323 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001324 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001325 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001326 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001327 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001328}
1329
Dan Stoza9e56aa02015-11-02 13:00:03 -08001330void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001331 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001332 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001333 getHwComposer().setVsyncEnabled(disp,
1334 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001335}
1336
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001337// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001338void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001339 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001340 // Clear the drawing state so that the logic inside of
1341 // handleTransactionLocked will fire. It will determine the delta between
1342 // mCurrentState and mDrawingState and re-apply all changes when we make the
1343 // transition.
1344 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001345 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001346 mDisplays.clear();
1347}
1348
Steven Thomas050b2c82017-03-06 11:45:16 -08001349void SurfaceFlinger::updateVrFlinger() {
1350 if (!mVrFlinger)
1351 return;
1352 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001353 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001354 return;
1355 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001356
David Sodman105b7dc2017-11-04 20:28:14 -07001357 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001358 ALOGE("Vr flinger is only supported for remote hardware composer"
1359 " service connections. Ignoring request to transition to vr"
1360 " flinger.");
1361 mVrFlingerRequestsDisplay = false;
1362 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001363 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001364
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001365 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001366
Steven Thomas0123ac62018-07-12 11:32:34 -07001367 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001368 LOG_ALWAYS_FATAL_IF(!display);
1369 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001370 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1371 // called below. Clear the reference now so we don't accidentally use it
1372 // later.
1373 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001374
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001376 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001377 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001378
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001380 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001381 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1382 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001383 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001384
David Sodman105b7dc2017-11-04 20:28:14 -07001385 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1386 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001387
1388 if (vrFlingerRequestsDisplay) {
1389 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001390 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001391
1392 mVisibleRegionsDirty = true;
1393 invalidateHwcGeometry();
1394
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001395 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001396 display = getDefaultDisplayDeviceLocked();
1397 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001398 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001399
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001401 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001402 const nsecs_t period = activeConfig->getVsyncPeriod();
1403 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001404
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001405 // The present fences returned from vr_hwc are not an accurate
1406 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001407 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1408 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001409
Steven Thomasb02664d2017-07-26 18:48:28 -07001410 // Use phase of 0 since phase is not known.
1411 // Use latency of 0, which will snap to the ideal latency.
1412 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001413
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001414 resyncToHardwareVsync(false);
1415
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001416 android_atomic_or(1, &mRepaintEverything);
1417 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001418}
1419
Mathias Agopian4fec8732012-06-29 14:12:52 -07001420void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001421 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001422 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001423 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001424 bool frameMissed = !mHadClientComposition &&
1425 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001426 (mPreviousPresentFence->getSignalTime() ==
1427 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001428 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001429 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001430 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001431 mTimeStats.incrementMissedFrames();
1432 if (mPropagateBackpressure) {
1433 signalLayerUpdate();
1434 break;
1435 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001436 }
Dan Stoza50182882016-07-08 12:02:20 -07001437
Steven Thomas050b2c82017-03-06 11:45:16 -08001438 // Now that we're going to make it to the handleMessageTransaction()
1439 // call below it's safe to call updateVrFlinger(), which will
1440 // potentially trigger a display handoff.
1441 updateVrFlinger();
1442
Dan Stoza6b9454d2014-11-07 16:00:59 -08001443 bool refreshNeeded = handleMessageTransaction();
1444 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001445 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001446 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001447 // Signal a refresh if a transaction modified the window state,
1448 // a new buffer was latched, or if HWC has requested a full
1449 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001450 signalRefresh();
1451 }
1452 break;
1453 }
1454 case MessageQueue::REFRESH: {
1455 handleMessageRefresh();
1456 break;
1457 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001458 }
1459}
1460
Dan Stoza6b9454d2014-11-07 16:00:59 -08001461bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001462 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001463 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001464 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001465 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001466 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001467 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001468}
1469
Mathias Agopian4fec8732012-06-29 14:12:52 -07001470void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001471 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001472
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001473 mRefreshPending = false;
1474
David Sodmanfa9b2af2017-12-24 13:28:59 -08001475 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001476 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001477 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001478 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001479 for (const auto& [token, display] : mDisplays) {
1480 beginFrame(display);
1481 prepareFrame(display);
1482 doDebugFlashRegions(display, repaintEverything);
1483 doComposition(display, repaintEverything);
1484 }
1485
Adrian Roos1e1a1282017-11-01 19:05:31 +01001486 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001487 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001488
1489 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001490 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001491
Dan Stozabfbffeb2016-07-21 14:49:33 -07001492 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001493 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001494 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001495 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001496 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001497
Jorim Jaggi90535212018-05-23 23:44:06 +02001498 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001499
David Sodman7e4ae112018-02-09 15:02:28 -08001500 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001501 for (const auto& [token, display] : mDisplays) {
1502 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001503 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001504 compositionInfo.hwc.hwcLayer = nullptr;
1505 }
David Sodmanba340492018-08-05 21:51:33 -07001506 }
David Sodman7e4ae112018-02-09 15:02:28 -08001507
1508 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001509}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001510
David Sodmanfa9b2af2017-12-24 13:28:59 -08001511
1512bool SurfaceFlinger::handleMessageInvalidate() {
1513 ATRACE_CALL();
1514 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001515}
1516
David Sodman79bba0e2018-08-05 18:07:49 -07001517void SurfaceFlinger::calculateWorkingSet() {
1518 ATRACE_CALL();
1519 ALOGV(__FUNCTION__);
1520
David Sodman79bba0e2018-08-05 18:07:49 -07001521 // build the h/w work list
1522 if (CC_UNLIKELY(mGeometryInvalid)) {
1523 mGeometryInvalid = false;
1524 for (const auto& [token, display] : mDisplays) {
1525 const auto displayId = display->getId();
1526 if (displayId >= 0) {
1527 const Vector<sp<Layer>>& currentLayers(
1528 display->getVisibleLayersSortedByZ());
1529 for (size_t i = 0; i < currentLayers.size(); i++) {
1530 const auto& layer = currentLayers[i];
1531
1532 if (!layer->hasHwcLayer(displayId)) {
1533 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1534 layer->forceClientComposition(displayId);
1535 continue;
1536 }
1537 }
1538
1539 layer->setGeometry(display, i);
1540 if (mDebugDisableHWC || mDebugRegion) {
1541 layer->forceClientComposition(displayId);
1542 }
1543 }
1544 }
1545 }
1546 }
1547
1548 // Set the per-frame data
1549 for (const auto& [token, display] : mDisplays) {
1550 const auto displayId = display->getId();
1551 if (displayId < 0) {
1552 continue;
1553 }
1554
1555 if (mDrawingState.colorMatrixChanged) {
1556 display->setColorTransform(mDrawingState.colorMatrix);
1557 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1558 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1559 "display %d: %d", displayId, result);
1560 }
1561 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1562 if (layer->isHdrY410()) {
1563 layer->forceClientComposition(displayId);
1564 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1565 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1566 !display->hasHDR10Support()) {
1567 layer->forceClientComposition(displayId);
1568 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1569 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1570 !display->hasHLGSupport()) {
1571 layer->forceClientComposition(displayId);
1572 }
1573
1574 if (layer->getForceClientComposition(displayId)) {
1575 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1576 layer->setCompositionType(displayId, HWC2::Composition::Client);
1577 continue;
1578 }
1579
1580 layer->setPerFrameData(display);
1581 }
1582
Peiyong Lin13effd12018-07-24 17:01:47 -07001583 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001584 ColorMode colorMode;
1585 Dataspace dataSpace;
1586 RenderIntent renderIntent;
1587 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1588 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1589 }
1590 }
1591
1592 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001593
1594 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001595 const auto displayId = display->getId();
1596 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001597 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1598 auto displayId = display->getId();
1599 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1600 if (!layer->setHwcLayer(displayId)) {
1601 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1602 }
David Sodman15fb96e2018-01-07 10:23:24 -08001603 layer->getBE().compositionInfo.hwc.displayId = displayId;
1604 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001605 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1606 }
1607 }
David Sodman79bba0e2018-08-05 18:07:49 -07001608}
1609
David Sodmanfa9b2af2017-12-24 13:28:59 -08001610void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001611{
1612 // is debugging enabled
1613 if (CC_LIKELY(!mDebugRegion))
1614 return;
1615
David Sodmanfa9b2af2017-12-24 13:28:59 -08001616 if (display->isPoweredOn()) {
1617 // transform the dirty region into this screen's coordinate space
1618 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1619 if (!dirtyRegion.isEmpty()) {
1620 // redraw the whole screen
1621 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001622
David Sodmanfa9b2af2017-12-24 13:28:59 -08001623 // and draw the dirty region
1624 const int32_t height = display->getHeight();
1625 auto& engine(getRenderEngine());
1626 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001627
David Sodmanfa9b2af2017-12-24 13:28:59 -08001628 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001629 }
1630 }
1631
David Sodmanfa9b2af2017-12-24 13:28:59 -08001632 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001633
1634 if (mDebugRegion > 1) {
1635 usleep(mDebugRegion * 1000);
1636 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001637
David Sodmanfa9b2af2017-12-24 13:28:59 -08001638 if (display->isPoweredOn()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001639 status_t result = display->prepareFrame(*getBE().mHwc);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001640 ALOGE_IF(result != NO_ERROR,
1641 "prepareFrame for display %d failed:"
1642 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001643 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001644 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001645}
1646
Adrian Roos1e1a1282017-11-01 19:05:31 +01001647void SurfaceFlinger::doTracing(const char* where) {
1648 ATRACE_CALL();
1649 ATRACE_NAME(where);
1650 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001651 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001652 }
1653}
1654
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001655void SurfaceFlinger::logLayerStats() {
1656 ATRACE_CALL();
1657 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001658 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001659 if (display->isPrimary()) {
1660 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001661 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001662 }
1663 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001664
1665 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001666 }
1667}
1668
David Sodman2b406362017-12-15 13:33:47 -08001669void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001670{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001671 ATRACE_CALL();
1672 ALOGV("preComposition");
1673
David Sodman2b406362017-12-15 13:33:47 -08001674 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1675
Mathias Agopiancd60f992012-08-16 16:28:27 -07001676 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001677 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001678 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001679 needExtraInvalidate = true;
1680 }
Robert Carr2047fae2016-11-28 14:09:09 -08001681 });
1682
Mathias Agopiancd60f992012-08-16 16:28:27 -07001683 if (needExtraInvalidate) {
1684 signalLayerUpdate();
1685 }
1686}
1687
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001688void SurfaceFlinger::updateCompositorTiming(
1689 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1690 std::shared_ptr<FenceTime>& presentFenceTime) {
1691 // Update queue of past composite+present times and determine the
1692 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001693 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001694 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001695 while (!getBE().mCompositePresentTimes.empty()) {
1696 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001697 // Cached values should have been updated before calling this method,
1698 // which helps avoid duplicate syscalls.
1699 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1700 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1701 break;
1702 }
1703 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001704 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001705 }
1706
1707 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001708 while (getBE().mCompositePresentTimes.size() > 16) {
1709 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001710 }
1711
Brian Andersond0010582017-03-07 13:20:31 -08001712 setCompositorTimingSnapped(
1713 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1714}
1715
1716void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1717 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001718 // Integer division and modulo round toward 0 not -inf, so we need to
1719 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001720 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001721 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1722 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1723
Brian Andersond0010582017-03-07 13:20:31 -08001724 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1725 if (idealLatency <= 0) {
1726 idealLatency = vsyncInterval;
1727 }
1728
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001729 // Snap the latency to a value that removes scheduling jitter from the
1730 // composition and present times, which often have >1ms of jitter.
1731 // Reducing jitter is important if an app attempts to extrapolate
1732 // something (such as user input) to an accurate diasplay time.
1733 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1734 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001735 nsecs_t bias = vsyncInterval / 2;
1736 int64_t extraVsyncs =
1737 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1738 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1739 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001740
David Sodman99974d22017-11-28 12:04:33 -08001741 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1742 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1743 getBE().mCompositorTiming.interval = vsyncInterval;
1744 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001745}
1746
David Sodman2b406362017-12-15 13:33:47 -08001747void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001748{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001749 ATRACE_CALL();
1750 ALOGV("postComposition");
1751
Brian Anderson3546a3f2016-07-14 11:51:14 -07001752 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001753 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001754 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001755 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001756 }
1757
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001758 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001759 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001760
David Sodman73beded2017-11-15 11:56:06 -08001761 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001762 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001763 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001764 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001765 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001766 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001767 } else {
1768 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1769 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001770
David Sodman73beded2017-11-15 11:56:06 -08001771 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001772 mPreviousPresentFence =
1773 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1774 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001775 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001776
Lloyd Pique41be5d22018-06-21 13:11:48 -07001777 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1778 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001779
David Sodman2b406362017-12-15 13:33:47 -08001780 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001781 // when we started doing work for this frame, but that should be okay
1782 // since updateCompositorTiming has snapping logic.
1783 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001784 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001785 CompositorTiming compositorTiming;
1786 {
David Sodman99974d22017-11-28 12:04:33 -08001787 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1788 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001789 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001790
Robert Carr2047fae2016-11-28 14:09:09 -08001791 mDrawingState.traverseInZOrder([&](Layer* layer) {
1792 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001793 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001794 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001795 recordBufferingStats(layer->getName().string(),
1796 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001797 }
Robert Carr2047fae2016-11-28 14:09:09 -08001798 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001799
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001800 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001801 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001802 enableHardwareVsync();
1803 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001804 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001805 }
1806 }
1807
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001808 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001809 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001810 enableHardwareVsync();
1811 }
1812 }
1813
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001814 if (mAnimCompositionPending) {
1815 mAnimCompositionPending = false;
1816
Brian Anderson4e606e32017-03-16 15:34:57 -07001817 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001818 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001819 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001820 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001821 // The HWC doesn't support present fences, so use the refresh
1822 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001823 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001824 mAnimFrameTracker.setActualPresentTime(presentTime);
1825 }
1826 mAnimFrameTracker.advanceFrame();
1827 }
Dan Stozab90cf072015-03-05 11:05:59 -08001828
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001829 mTimeStats.incrementTotalFrames();
1830 if (mHadClientComposition) {
1831 mTimeStats.incrementClientCompositionFrames();
1832 }
1833
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001834 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001835 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001836 return;
1837 }
1838
1839 nsecs_t currentTime = systemTime();
1840 if (mHasPoweredOff) {
1841 mHasPoweredOff = false;
1842 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001843 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001844 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001845 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1846 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001847 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001848 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001849 }
David Sodman4a36e932017-11-07 14:29:47 -08001850 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001851 }
David Sodman4a36e932017-11-07 14:29:47 -08001852 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001853
1854 {
1855 std::lock_guard lock(mTexturePoolMutex);
1856 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1857 if (refillCount > 0) {
1858 const size_t offset = mTexturePool.size();
1859 mTexturePool.resize(mTexturePoolSize);
1860 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1861 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1862 }
1863 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864}
1865
1866void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001867 ATRACE_CALL();
1868 ALOGV("rebuildLayerStacks");
1869
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001871 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001872 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001873 mVisibleRegionsDirty = false;
1874 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001875
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001876 for (const auto& pair : mDisplays) {
1877 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001878 Region opaqueRegion;
1879 Region dirtyRegion;
1880 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001881 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001882 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001883 const Rect bounds = display->getBounds();
1884 if (display->isPoweredOn()) {
1885 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001886
Jeff Sharkey76488112017-02-27 14:15:18 -07001887 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001888 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001889 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001890 Region drawRegion(tr.transform(
1891 layer->visibleNonTransparentRegion));
1892 drawRegion.andSelf(bounds);
1893 if (!drawRegion.isEmpty()) {
1894 layersSortedByZ.add(layer);
1895 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001896 // Clear out the HWC layer if this layer was
1897 // previously visible, but no longer is
1898 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001899 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001900 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001901 // WM changes display->layerStack upon sleep/awake.
1902 // Here we make sure we delete the HWC layers even if
1903 // WM changed their layer stack.
1904 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001905 }
1906
1907 // If a layer is not going to get a release fence because
1908 // it is invisible, but it is also going to release its
1909 // old buffer, add it to the list of layers needing
1910 // fences.
1911 if (hwcLayerDestroyed) {
1912 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1913 mLayersWithQueuedFrames.cend(), layer);
1914 if (found != mLayersWithQueuedFrames.cend()) {
1915 layersNeedingFences.add(layer);
1916 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001917 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001918 });
1919 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001920 display->setVisibleLayersSortedByZ(layersSortedByZ);
1921 display->setLayersNeedingFences(layersNeedingFences);
1922 display->undefinedRegion.set(bounds);
1923 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1924 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001925 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001926 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001927}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001928
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001929// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001930// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001931// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001932// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001933// The returned HDR data space is one of
1934// - Dataspace::UNKNOWN
1935// - Dataspace::BT2020_HLG
1936// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001937Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1938 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001939 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001940 *outHdrDataSpace = Dataspace::UNKNOWN;
1941
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001942 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001943 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001944 case Dataspace::V0_SCRGB:
1945 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001946 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001947 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001948 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001949 case Dataspace::BT2020_PQ:
1950 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001951 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001952 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001953 case Dataspace::BT2020_HLG:
1954 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001955 // When there's mixed PQ content and HLG content, we set the HDR
1956 // data space to be BT2020_PQ and convert HLG to PQ.
1957 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1958 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001959 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001960 break;
1961 default:
1962 break;
1963 }
Romain Guy54f154a2017-10-24 21:40:32 +01001964 }
1965
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001966 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001967}
1968
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001969// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001970void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1971 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001972 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1973 *outMode = ColorMode::NATIVE;
1974 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001975 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001976 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001977 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001978
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001979 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001980 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001981
Peiyong Lindfde5112018-06-05 10:58:41 -07001982 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001983 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001984 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001985 if (isHdr) {
1986 bestDataSpace = hdrDataSpace;
1987 }
1988
Chia-I Wu0d711262018-05-21 15:19:35 -07001989 RenderIntent intent;
1990 switch (mDisplayColorSetting) {
1991 case DisplayColorSetting::MANAGED:
1992 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001993 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001994 break;
1995 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001996 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001997 break;
1998 default: // vendor display color setting
1999 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2000 break;
2001 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002003 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002004}
2005
David Sodmanfa9b2af2017-12-24 13:28:59 -08002006void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002007{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002008 bool dirty = !display->getDirtyRegion(false).isEmpty();
2009 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2010 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002011
David Sodmanfa9b2af2017-12-24 13:28:59 -08002012 // If nothing has changed (!dirty), don't recompose.
2013 // If something changed, but we don't currently have any visible layers,
2014 // and didn't when we last did a composition, then skip it this time.
2015 // The second rule does two things:
2016 // - When all layers are removed from a display, we'll emit one black
2017 // frame, then nothing more until we get new layers.
2018 // - When a display is created with a private layer stack, we won't
2019 // emit any black frames until a layer is added to the layer stack.
2020 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002021
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002022 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2023 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002024 mustRecompose ? "doing" : "skipping",
2025 dirty ? "+" : "-",
2026 empty ? "+" : "-",
2027 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002028
David Sodmanfa9b2af2017-12-24 13:28:59 -08002029 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002030
David Sodmanfa9b2af2017-12-24 13:28:59 -08002031 if (mustRecompose) {
2032 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002033 }
2034}
2035
David Sodmanfa9b2af2017-12-24 13:28:59 -08002036void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002037{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002038 if (!display->isPoweredOn()) {
2039 return;
David Sodman2b406362017-12-15 13:33:47 -08002040 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002041
2042 status_t result = display->prepareFrame(*getBE().mHwc);
2043 ALOGE_IF(result != NO_ERROR,
2044 "prepareFrame for display %d failed:"
2045 " %d (%s)",
2046 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002047}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002048
David Sodmanfa9b2af2017-12-24 13:28:59 -08002049void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002050 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 ALOGV("doComposition");
2052
David Sodmanfa9b2af2017-12-24 13:28:59 -08002053 if (display->isPoweredOn()) {
2054 // transform the dirty region into this screen's coordinate space
2055 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002056
David Sodmanfa9b2af2017-12-24 13:28:59 -08002057 // repaint the framebuffer (if needed)
2058 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002059
David Sodmanfa9b2af2017-12-24 13:28:59 -08002060 display->dirtyRegion.clear();
2061 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002062 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002063 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002064}
2065
David Sodmanfa9b2af2017-12-24 13:28:59 -08002066void SurfaceFlinger::postFrame()
2067{
2068 // |mStateLock| not needed as we are on the main thread
2069 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2070 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2071 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2072 logFrameStats();
2073 }
2074 }
2075}
2076
2077void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002078{
Mathias Agopian841cde52012-03-01 15:44:37 -08002079 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002080 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002081
David Sodmanfa9b2af2017-12-24 13:28:59 -08002082 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002083
David Sodmanfa9b2af2017-12-24 13:28:59 -08002084 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002085 const auto displayId = display->getId();
2086 if (displayId >= 0) {
2087 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002088 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002089 display->onSwapBuffersCompleted();
2090 display->makeCurrent();
2091 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002092 sp<Fence> releaseFence = Fence::NO_FENCE;
2093
Chia-I Wu7b549592017-11-15 09:14:57 -08002094 // The layer buffer from the previous frame (if any) is released
2095 // by HWC only when the release fence from this frame (if any) is
2096 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002097 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002098 if (displayId >= 0) {
2099 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2100 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002101
2102 // If the layer was client composited in the previous frame, we
2103 // need to merge with the previous client target acquire fence.
2104 // Since we do not track that, always merge with the current
2105 // client target acquire fence when it is available, even though
2106 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002107 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002108 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002109 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002110 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002111
David Sodmanb8af7922017-12-21 15:17:55 -08002112 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002113 }
Chia-I Wu83806892017-11-16 10:50:20 -08002114
2115 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002116 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002117 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002118 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002119 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002120 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002121 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002122 }
2123 }
2124
Dominik Laskowski7e045462018-05-30 13:02:02 -07002125 if (displayId >= 0) {
2126 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002127 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002128 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002129}
2130
Mathias Agopian87baae12012-07-31 12:38:26 -07002131void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002132{
Mathias Agopian841cde52012-03-01 15:44:37 -08002133 ATRACE_CALL();
2134
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002135 // here we keep a copy of the drawing state (that is the state that's
2136 // going to be overwritten by handleTransactionLocked()) outside of
2137 // mStateLock so that the side-effects of the State assignment
2138 // don't happen with mStateLock held (which can cause deadlocks).
2139 State drawingState(mDrawingState);
2140
Mathias Agopianca4d3602011-05-19 15:38:14 -07002141 Mutex::Autolock _l(mStateLock);
2142 const nsecs_t now = systemTime();
2143 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002144
Mathias Agopianca4d3602011-05-19 15:38:14 -07002145 // Here we're guaranteed that some transaction flags are set
2146 // so we can call handleTransactionLocked() unconditionally.
2147 // We call getTransactionFlags(), which will also clear the flags,
2148 // with mStateLock held to guarantee that mCurrentState won't change
2149 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002150
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002151 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002152 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002153 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002154
Mathias Agopianca4d3602011-05-19 15:38:14 -07002155 mLastTransactionTime = systemTime() - now;
2156 mDebugInTransaction = 0;
2157 invalidateHwcGeometry();
2158 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002159}
2160
Dominik Laskowski7e045462018-05-30 13:02:02 -07002161DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002162 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002163 // Figure out whether the event is for the primary display or an
2164 // external display by matching the Hwc display id against one for a
2165 // connected display. If we did not find a match, we then check what
2166 // displays are not already connected to determine the type. If we don't
2167 // have a connected primary display, we assume the new display is meant to
2168 // be the primary display, and then if we don't have an external display,
2169 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002170 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2171 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002172 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002173 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002174 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002175 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002176 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002177 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002178 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002179 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002180 return DisplayDevice::DISPLAY_EXTERNAL;
2181 }
2182
2183 return DisplayDevice::DISPLAY_ID_INVALID;
2184}
2185
Lloyd Piqueba04e622017-12-14 17:11:26 -08002186void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2187 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002188 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002189 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002190 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002191 continue;
2192 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002193
2194 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2195 ALOGE("External displays are not supported by the vr hardware composer.");
2196 continue;
2197 }
2198
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002199 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002200 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002201 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002202 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002203 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002204
2205 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002206 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002207 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002208 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002209 DisplayDeviceState info;
2210 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002211 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2212 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002213 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002214 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002215 mInterceptor->saveDisplayCreation(info);
2216 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002217 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002218 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002219
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002220 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002221 if (idx >= 0) {
2222 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002223 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002224 mCurrentState.displays.removeItemsAt(idx);
2225 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002226 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002227 }
2228
2229 processDisplayChangesLocked();
2230 }
2231
2232 mPendingHotplugEvents.clear();
2233}
2234
Lloyd Pique99d3da52018-01-22 17:48:03 -08002235sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002236 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002237 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002238 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002239 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002240 HdrCapabilities hdrCapabilities;
2241 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002242
Peiyong Lin13effd12018-07-24 17:01:47 -07002243 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002244 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002245 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002246 if (isWideColorMode(colorMode)) {
2247 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002248 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002249
Dominik Laskowski7e045462018-05-30 13:02:02 -07002250 std::vector<RenderIntent> renderIntents =
2251 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002252 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002253 }
tangrobin6753a022018-08-10 10:58:54 +08002254 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002255
tangrobin6753a022018-08-10 10:58:54 +08002256 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002257 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2258 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2259 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002260
2261 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2262 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2263
2264 /*
2265 * Create our display's surface
2266 */
2267 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2268 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002269 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002270 renderSurface->setNativeWindow(nativeWindow.get());
2271 const int displayWidth = renderSurface->queryWidth();
2272 const int displayHeight = renderSurface->queryHeight();
2273
2274 // Make sure that composition can never be stalled by a virtual display
2275 // consumer that isn't processing buffers fast enough. We have to do this
2276 // in two places:
2277 // * Here, in case the display is composed entirely by HWC.
2278 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2279 // window's swap interval in eglMakeCurrent, so they'll override the
2280 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002281 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002282 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2283 }
2284
2285 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002286 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002287
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002288 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002289 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2290 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2291 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002292 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002293
2294 if (maxFrameBufferAcquiredBuffers >= 3) {
2295 nativeWindowSurface->preallocateBuffers();
2296 }
2297
2298 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002299 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2300 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002301 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002302 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002303 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002304 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002305 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002306 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002307 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002308 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002309 display->setLayerStack(state.layerStack);
2310 display->setProjection(state.orientation, state.viewport, state.frame);
2311 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002312
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002313 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002314}
2315
Lloyd Pique347200f2017-12-14 17:00:15 -08002316void SurfaceFlinger::processDisplayChangesLocked() {
2317 // here we take advantage of Vector's copy-on-write semantics to
2318 // improve performance by skipping the transaction entirely when
2319 // know that the lists are identical
2320 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2321 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2322 if (!curr.isIdenticalTo(draw)) {
2323 mVisibleRegionsDirty = true;
2324 const size_t cc = curr.size();
2325 size_t dc = draw.size();
2326
2327 // find the displays that were removed
2328 // (ie: in drawing state but not in current state)
2329 // also handle displays that changed
2330 // (ie: displays that are in both lists)
2331 for (size_t i = 0; i < dc;) {
2332 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2333 if (j < 0) {
2334 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002335 // Call makeCurrent() on the primary display so we can
2336 // be sure that nothing associated with this display
2337 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002338 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2339 defaultDisplay->makeCurrent();
2340 }
2341 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2342 display->disconnect(getHwComposer());
2343 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002344 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2345 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2346 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2347 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2348 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002349 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002350 } else {
2351 // this display is in both lists. see if something changed.
2352 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002353 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002354 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2355 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2356 if (state_binder != draw_binder) {
2357 // changing the surface is like destroying and
2358 // recreating the DisplayDevice, so we just remove it
2359 // from the drawing state, so that it get re-added
2360 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002361 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2362 display->disconnect(getHwComposer());
2363 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002364 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002365 mDrawingState.displays.removeItemsAt(i);
2366 dc--;
2367 // at this point we must loop to the next item
2368 continue;
2369 }
2370
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002371 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002372 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002373 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002374 }
2375 if ((state.orientation != draw[i].orientation) ||
2376 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002377 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002378 }
2379 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002380 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002381 }
2382 }
2383 }
2384 ++i;
2385 }
2386
2387 // find displays that were added
2388 // (ie: in current state but not in drawing state)
2389 for (size_t i = 0; i < cc; i++) {
2390 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2391 const DisplayDeviceState& state(curr[i]);
2392
2393 sp<DisplaySurface> dispSurface;
2394 sp<IGraphicBufferProducer> producer;
2395 sp<IGraphicBufferProducer> bqProducer;
2396 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002397 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002398
Dominik Laskowski7e045462018-05-30 13:02:02 -07002399 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002400 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002401 // Virtual displays without a surface are dormant:
2402 // they have external state (layer stack, projection,
2403 // etc.) but no internal state (i.e. a DisplayDevice).
2404 if (state.surface != nullptr) {
2405 // Allow VR composer to use virtual displays.
2406 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2407 int width = 0;
2408 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2409 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2410 int height = 0;
2411 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2412 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2413 int intFormat = 0;
2414 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2415 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002416 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002417
Dominik Laskowski7e045462018-05-30 13:02:02 -07002418 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2419 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002420 }
2421
2422 // TODO: Plumb requested format back up to consumer
2423
2424 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002425 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002426 bqProducer, bqConsumer,
2427 state.displayName);
2428
2429 dispSurface = vds;
2430 producer = vds;
2431 }
2432 } else {
2433 ALOGE_IF(state.surface != nullptr,
2434 "adding a supported display, but rendering "
2435 "surface is provided (%p), ignoring it",
2436 state.surface.get());
2437
Dominik Laskowski7e045462018-05-30 13:02:02 -07002438 displayId = state.type;
2439 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002440 producer = bqProducer;
2441 }
2442
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002443 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002444 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002445 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002446 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002447 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002448 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002449 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2450 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2451 true);
2452 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2453 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2454 true);
2455 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002456 }
2457 }
2458 }
2459 }
2460 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002461
2462 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002463}
2464
Mathias Agopian87baae12012-07-31 12:38:26 -07002465void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002466{
Dan Stoza7dde5992015-05-22 09:51:44 -07002467 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002468 mCurrentState.traverseInZOrder([](Layer* layer) {
2469 layer->notifyAvailableFrames();
2470 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002471
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002472 /*
2473 * Traversal of the children
2474 * (perform the transaction for each of them if needed)
2475 */
2476
Mathias Agopian3559b072012-08-15 13:46:03 -07002477 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002478 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002479 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002480 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002481
2482 const uint32_t flags = layer->doTransaction(0);
2483 if (flags & Layer::eVisibleRegion)
2484 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002485 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486 }
2487
2488 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002489 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002490 */
2491
Mathias Agopiane57f2922012-08-09 16:29:12 -07002492 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002493 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002494 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002495 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002497 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002498 // The transform hint might have changed for some layers
2499 // (either because a display has changed, or because a layer
2500 // as changed).
2501 //
2502 // Walk through all the layers in currentLayers,
2503 // and update their transform hint.
2504 //
2505 // If a layer is visible only on a single display, then that
2506 // display is used to calculate the hint, otherwise we use the
2507 // default display.
2508 //
2509 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2510 // the hint is set before we acquire a buffer from the surface texture.
2511 //
2512 // NOTE: layer transactions have taken place already, so we use their
2513 // drawing state. However, SurfaceFlinger's own transaction has not
2514 // happened yet, so we must use the current state layer list
2515 // (soon to become the drawing state list).
2516 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002517 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002518 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002519 bool first = true;
2520 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002521 // NOTE: we rely on the fact that layers are sorted by
2522 // layerStack first (so we don't have to traverse the list
2523 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002524 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002525 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002526 currentlayerStack = layerStack;
2527 // figure out if this layerstack is mirrored
2528 // (more than one display) if so, pick the default display,
2529 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002530 hintDisplay = nullptr;
2531 for (const auto& [token, display] : mDisplays) {
2532 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2533 if (hintDisplay) {
2534 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002535 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002536 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002537 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002538 }
2539 }
2540 }
2541 }
Chet Haase91d25932013-04-11 15:24:55 -07002542
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002543 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002544 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2545 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002546
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002547 // could be null when this layer is using a layerStack
2548 // that is not visible on any display. Also can occur at
2549 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002550 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002551 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002552
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002553 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002554 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002555 if (hintDisplay) {
2556 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002557 }
Robert Carr2047fae2016-11-28 14:09:09 -08002558
2559 first = false;
2560 });
Mathias Agopian84300952012-11-21 16:02:13 -08002561 }
2562
2563
Mathias Agopian3559b072012-08-15 13:46:03 -07002564 /*
2565 * Perform our own transaction if needed
2566 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002567
2568 if (mLayersAdded) {
2569 mLayersAdded = false;
2570 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002571 mVisibleRegionsDirty = true;
2572 }
2573
2574 // some layers might have been removed, so
2575 // we need to update the regions they're exposing.
2576 if (mLayersRemoved) {
2577 mLayersRemoved = false;
2578 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002579 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002580 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002581 // this layer is not visible anymore
2582 // TODO: we could traverse the tree from front to back and
2583 // compute the actual visible region
2584 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002585 Region visibleReg;
2586 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002587 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002588 }
Robert Carr2047fae2016-11-28 14:09:09 -08002589 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590 }
2591
2592 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002593
2594 updateCursorAsync();
2595}
2596
2597void SurfaceFlinger::updateCursorAsync()
2598{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002599 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002600 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002601 continue;
2602 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002603
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002604 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2605 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002606 }
2607 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002608}
2609
2610void SurfaceFlinger::commitTransaction()
2611{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002612 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002613 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002614 for (const auto& l : mLayersPendingRemoval) {
2615 recordBufferingStats(l->getName().string(),
2616 l->getOccupancyHistory(true));
2617 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002618 }
2619 mLayersPendingRemoval.clear();
2620 }
2621
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002622 // If this transaction is part of a window animation then the next frame
2623 // we composite should be considered an animation as well.
2624 mAnimCompositionPending = mAnimTransactionPending;
2625
Mathias Agopian4fec8732012-06-29 14:12:52 -07002626 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002627 // clear the "changed" flags in current state
2628 mCurrentState.colorMatrixChanged = false;
2629
Robert Carr1f0a16a2016-10-24 16:27:39 -07002630 mDrawingState.traverseInZOrder([](Layer* layer) {
2631 layer->commitChildList();
2632 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002633 mTransactionPending = false;
2634 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002635 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636}
2637
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002638void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2639 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002640 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002641 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002642
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643 Region aboveOpaqueLayers;
2644 Region aboveCoveredLayers;
2645 Region dirty;
2646
Mathias Agopian87baae12012-07-31 12:38:26 -07002647 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648
Robert Carr2047fae2016-11-28 14:09:09 -08002649 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002650 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002651 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652
Jesse Hall01e29052013-02-19 16:13:35 -08002653 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002654 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002655 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002656 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002657
Mathias Agopianab028732010-03-16 16:41:46 -07002658 /*
2659 * opaqueRegion: area of a surface that is fully opaque.
2660 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002662
2663 /*
2664 * visibleRegion: area of a surface that is visible on screen
2665 * and not fully transparent. This is essentially the layer's
2666 * footprint minus the opaque regions above it.
2667 * Areas covered by a translucent surface are considered visible.
2668 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002669 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002670
2671 /*
2672 * coveredRegion: area of a surface that is covered by all
2673 * visible regions above it (which includes the translucent areas).
2674 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002675 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002676
Jesse Halla8026d22012-09-25 13:25:04 -07002677 /*
2678 * transparentRegion: area of a surface that is hinted to be completely
2679 * transparent. This is only used to tell when the layer has no visible
2680 * non-transparent regions and can be removed from the layer list. It
2681 * does not affect the visibleRegion of this layer or any layers
2682 * beneath it. The hint may not be correct if apps don't respect the
2683 * SurfaceView restrictions (which, sadly, some don't).
2684 */
2685 Region transparentRegion;
2686
Mathias Agopianab028732010-03-16 16:41:46 -07002687
2688 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002689 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002690 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002691 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002692 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002693 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002694 if (!visibleRegion.isEmpty()) {
2695 // Remove the transparent area from the visible region
2696 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002697 if (tr.preserveRects()) {
2698 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002699 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002700 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002701 // transformation too complex, can't do the
2702 // transparent region optimization.
2703 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002704 }
Mathias Agopianab028732010-03-16 16:41:46 -07002705 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002706
Mathias Agopianab028732010-03-16 16:41:46 -07002707 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002708 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002709 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002710 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002711 // the opaque region is the layer's footprint
2712 opaqueRegion = visibleRegion;
2713 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714 }
2715 }
2716
Robert Carre5f4f692018-01-12 13:12:28 -08002717 if (visibleRegion.isEmpty()) {
2718 layer->clearVisibilityRegions();
2719 return;
2720 }
2721
Mathias Agopianab028732010-03-16 16:41:46 -07002722 // Clip the covered region to the visible region
2723 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2724
2725 // Update aboveCoveredLayers for next (lower) layer
2726 aboveCoveredLayers.orSelf(visibleRegion);
2727
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002728 // subtract the opaque region covered by the layers above us
2729 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730
2731 // compute this layer's dirty region
2732 if (layer->contentDirty) {
2733 // we need to invalidate the whole region
2734 dirty = visibleRegion;
2735 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002736 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737 layer->contentDirty = false;
2738 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002739 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002740 * the exposed region consists of two components:
2741 * 1) what's VISIBLE now and was COVERED before
2742 * 2) what's EXPOSED now less what was EXPOSED before
2743 *
2744 * note that (1) is conservative, we start with the whole
2745 * visible region but only keep what used to be covered by
2746 * something -- which mean it may have been exposed.
2747 *
2748 * (2) handles areas that were not covered by anything but got
2749 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002750 */
Mathias Agopianab028732010-03-16 16:41:46 -07002751 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002752 const Region oldVisibleRegion = layer->visibleRegion;
2753 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002754 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2755 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756 }
2757 dirty.subtractSelf(aboveOpaqueLayers);
2758
2759 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002760 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761
Mathias Agopianab028732010-03-16 16:41:46 -07002762 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002764
Jesse Halla8026d22012-09-25 13:25:04 -07002765 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766 layer->setVisibleRegion(visibleRegion);
2767 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002768 layer->setVisibleNonTransparentRegion(
2769 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002770 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771
Mathias Agopian87baae12012-07-31 12:38:26 -07002772 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773}
2774
Chia-I Wuab0c3192017-08-01 11:29:00 -07002775void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002776 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002777 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2778 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002779 }
2780 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002781}
2782
Dan Stoza6b9454d2014-11-07 16:00:59 -08002783bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002784{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002785 ALOGV("handlePageFlip");
2786
Brian Andersond6927fb2016-07-23 23:37:30 -07002787 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788
Mathias Agopian4fec8732012-06-29 14:12:52 -07002789 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002790 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002791 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002792
2793 // Store the set of layers that need updates. This set must not change as
2794 // buffers are being latched, as this could result in a deadlock.
2795 // Example: Two producers share the same command stream and:
2796 // 1.) Layer 0 is latched
2797 // 2.) Layer 0 gets a new frame
2798 // 2.) Layer 1 gets a new frame
2799 // 3.) Layer 1 is latched.
2800 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2801 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002802 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002803 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002804 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002805 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002806 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002807 } else {
2808 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002809 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002810 } else {
2811 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002812 }
Robert Carr2047fae2016-11-28 14:09:09 -08002813 });
2814
Dan Stoza9e56aa02015-11-02 13:00:03 -08002815 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002816 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002817 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002818 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002819 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002820 newDataLatched = true;
2821 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002822 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002823
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002824 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002825
2826 // If we will need to wake up at some time in the future to deal with a
2827 // queued frame that shouldn't be displayed during this vsync period, wake
2828 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002829 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002830 signalLayerUpdate();
2831 }
2832
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002833 // enter boot animation on first buffer latch
2834 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2835 ALOGI("Enter boot animation");
2836 mBootStage = BootStage::BOOTANIMATION;
2837 }
2838
Dan Stoza6b9454d2014-11-07 16:00:59 -08002839 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002840 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841}
2842
Mathias Agopianad456f92011-01-13 17:53:01 -08002843void SurfaceFlinger::invalidateHwcGeometry()
2844{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002846}
2847
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002848void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2849 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002850 // We only need to actually compose the display if:
2851 // 1) It is being handled by hardware composer, which may need this to
2852 // keep its virtual display state machine in sync, or
2853 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002854 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002855 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002856 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002857 return;
2858 }
2859
Dan Stoza9e56aa02015-11-02 13:00:03 -08002860 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002861 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002862
2863 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002864 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865}
2866
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002867bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002868 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002869
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002870 const Region bounds(display->bounds());
2871 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002872 const auto displayId = display->getId();
2873 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002874 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002875
Chia-I Wu8e50e692018-05-04 10:12:37 -07002876 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002877 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002878
Dan Stoza9e56aa02015-11-02 13:00:03 -08002879 if (hasClientComposition) {
2880 ALOGV("hasClientComposition");
2881
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002882 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002883 if (display->hasWideColorGamut()) {
2884 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002885 }
2886 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002887 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002888 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002889
Dominik Laskowski7e045462018-05-30 13:02:02 -07002890 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002891 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2892 HWC2::Capability::SkipClientColorTransform);
2893
Chia-I Wud49d6692018-06-27 07:17:41 +08002894 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002895 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2896 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002897 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002898 }
2899
Chia-I Wud49d6692018-06-27 07:17:41 +08002900 // The current enhanced saturation matrix is designed to enhance Display P3,
2901 // thus we only apply this matrix when the render intent is not colorimetric
2902 // and the output color space is Display P3.
2903 needsEnhancedColorMatrix =
2904 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2905 outputDataspace == Dataspace::DISPLAY_P3);
2906 if (needsEnhancedColorMatrix) {
2907 colorMatrix *= mEnhancedSaturationMatrix;
2908 }
2909
2910 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002911
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002912 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002913 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002914 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002915 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002916
2917 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002918 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2919 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2920 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002921 }
2922 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002923 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002924
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002925 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002926 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002927 // when using overlays, we assume a fully transparent framebuffer
2928 // NOTE: we could reduce how much we need to clear, for instance
2929 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002930 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002931 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002932 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002933 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002934 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002935 // we're left with the letterbox region
2936 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002937 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002938
2939 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002940 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002941
Mathias Agopianb9494d52012-04-18 02:28:45 -07002942 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002943 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002944 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002945 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002946 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002947 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002948
Yiwei Zhange4e26c02018-08-22 13:59:12 -07002949 const Rect& bounds = display->getBounds();
2950 const Rect& scissor = display->getScissor();
2951 if (scissor != bounds) {
2952 // scissor doesn't match the screen's dimensions, so we
2953 // need to clear everything outside of it and enable
2954 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002955
Yiwei Zhange4e26c02018-08-22 13:59:12 -07002956 // enable scissor for this frame
2957 const uint32_t height = display->getHeight();
2958 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
2959 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002960 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002961 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002962
Mathias Agopian85d751c2012-08-29 16:59:24 -07002963 /*
2964 * and then, render the layers targeted at the framebuffer
2965 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002966
Dan Stoza9e56aa02015-11-02 13:00:03 -08002967 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07002968 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002969 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002970 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002971 const Region clip(bounds.intersect(
2972 displayTransform.transform(layer->visibleRegion)));
2973 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002974 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002975 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002976 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002977 case HWC2::Composition::Cursor:
2978 case HWC2::Composition::Device:
2979 case HWC2::Composition::Sideband:
2980 case HWC2::Composition::SolidColor: {
2981 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002982 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05302983 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
2984 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002985 // never clear the very first layer since we're
2986 // guaranteed the FB is already cleared
2987 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002988 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002989 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002990 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002991 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002992 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002993 break;
2994 }
2995 default:
2996 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002997 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002998 } else {
2999 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003000 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003001 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003002 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003003
Chia-I Wud49d6692018-06-27 07:17:41 +08003004 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003005 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003006 }
3007
Mathias Agopianf45c5102012-10-24 16:29:17 -07003008 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003009 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003010 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003011}
3012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003013void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3014 const Region& region) const {
3015 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003016 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003017 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003018}
3019
Dan Stoza7d89d062015-04-30 13:29:25 -07003020status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003021 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003022 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003023 const sp<Layer>& lbc,
3024 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003025{
Dan Stoza7d89d062015-04-30 13:29:25 -07003026 // add this layer to the current state list
3027 {
3028 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003029 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003030 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3031 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003032 return NO_MEMORY;
3033 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003034 if (parent == nullptr) {
3035 mCurrentState.layersSortedByZ.add(lbc);
3036 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003037 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003038 ALOGE("addClientLayer called with a removed parent");
3039 return NAME_NOT_FOUND;
3040 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003041 parent->addChild(lbc);
3042 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003043
Yiwei Zhang243b3782018-05-15 17:40:04 -07003044 if (gbc != nullptr) {
3045 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3046 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3047 mMaxGraphicBufferProducerListSize,
3048 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3049 mGraphicBufferProducerList.size(),
3050 mMaxGraphicBufferProducerListSize, mNumLayers);
3051 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003052 mLayersAdded = true;
3053 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003054 }
3055
Mathias Agopian96f08192010-06-02 23:28:45 -07003056 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003057 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003058
Dan Stoza7d89d062015-04-30 13:29:25 -07003059 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003060}
3061
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003062status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003063 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003064 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3065}
Robert Carr7f9b8992017-03-10 11:08:39 -08003066
chaviwca27f252018-02-06 16:46:39 -08003067status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3068 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003069 if (layer->isPendingRemoval()) {
3070 return NO_ERROR;
3071 }
3072
Robert Carr1f0a16a2016-10-24 16:27:39 -07003073 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003074 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003075 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003076 if (topLevelOnly) {
3077 return NO_ERROR;
3078 }
3079
Chia-I Wu98f1c102017-05-30 14:54:08 -07003080 sp<Layer> ancestor = p;
3081 while (ancestor->getParent() != nullptr) {
3082 ancestor = ancestor->getParent();
3083 }
3084 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3085 ALOGE("removeLayer called with a layer whose parent has been removed");
3086 return NAME_NOT_FOUND;
3087 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003088
3089 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003090 } else {
3091 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003092 }
3093
Robert Carr136e2f62017-02-08 17:54:29 -08003094 // As a matter of normal operation, the LayerCleaner will produce a second
3095 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3096 // so we will succeed in promoting it, but it's already been removed
3097 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3098 // otherwise something has gone wrong and we are leaking the layer.
3099 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003100 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3101 layer->getName().string(),
3102 (p != nullptr) ? p->getName().string() : "no-parent");
3103 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003104 } else if (index < 0) {
3105 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003106 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003107
Chia-I Wuc6657022017-08-15 11:18:17 -07003108 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003109 mLayersPendingRemoval.add(layer);
3110 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003111 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003112 setTransactionFlags(eTransactionNeeded);
3113 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003114}
3115
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003116uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003117 return android_atomic_release_load(&mTransactionFlags);
3118}
3119
Mathias Agopian3f844832013-08-07 21:24:32 -07003120uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3122}
3123
Mathias Agopian3f844832013-08-07 21:24:32 -07003124uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003125 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3126}
3127
3128uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3129 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003130 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003131 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003133 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134 }
3135 return old;
3136}
3137
chaviwca27f252018-02-06 16:46:39 -08003138bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3139 for (const ComposerState& state : states) {
3140 // Here we need to check that the interface we're given is indeed
3141 // one of our own. A malicious client could give us a nullptr
3142 // IInterface, or one of its own or even one of our own but a
3143 // different type. All these situations would cause us to crash.
3144 if (state.client == nullptr) {
3145 return true;
3146 }
3147
3148 sp<IBinder> binder = IInterface::asBinder(state.client);
3149 if (binder == nullptr) {
3150 return true;
3151 }
3152
3153 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3154 return true;
3155 }
3156 }
3157 return false;
3158}
3159
Mathias Agopian8b33f032012-07-24 20:43:54 -07003160void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003161 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003162 const Vector<DisplayState>& displays,
3163 uint32_t flags)
3164{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003165 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003166 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003167 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003168
chaviwca27f252018-02-06 16:46:39 -08003169 if (containsAnyInvalidClientState(states)) {
3170 return;
3171 }
3172
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003173 if (flags & eAnimation) {
3174 // For window updates that are part of an animation we must wait for
3175 // previous animation "frames" to be handled.
3176 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003177 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003178 if (CC_UNLIKELY(err != NO_ERROR)) {
3179 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003180 // caller after a few seconds.
3181 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3182 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003183 mAnimTransactionPending = false;
3184 break;
3185 }
3186 }
3187 }
3188
chaviwca27f252018-02-06 16:46:39 -08003189 for (const DisplayState& display : displays) {
3190 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003191 }
3192
chaviwca27f252018-02-06 16:46:39 -08003193 for (const ComposerState& state : states) {
3194 transactionFlags |= setClientStateLocked(state);
3195 }
3196
3197 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3198 // as destroyed should only occur after setting all other states. This is to allow for a
3199 // child re-parent to happen before marking its original parent as destroyed (which would
3200 // then mark the child as destroyed).
3201 for (const ComposerState& state : states) {
3202 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003203 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003204
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003205 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3206 // anyway. This can be used as a flush mechanism for previous async transactions.
3207 // Empty animation transaction can be used to simulate back-pressure, so also force a
3208 // transaction for empty animation transactions.
3209 if (transactionFlags == 0 &&
3210 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003211 transactionFlags = eTransactionNeeded;
3212 }
3213
Mathias Agopian386aa982011-11-07 21:58:03 -08003214 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003215 if (mInterceptor->isEnabled()) {
3216 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003217 }
Irvel468051e2016-06-13 16:44:44 -07003218
Mathias Agopian386aa982011-11-07 21:58:03 -08003219 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003220 const auto start = (flags & eEarlyWakeup)
3221 ? VSyncModulator::TransactionStart::EARLY
3222 : VSyncModulator::TransactionStart::NORMAL;
3223 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003224
3225 // if this is a synchronous transaction, wait for it to take effect
3226 // before returning.
3227 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003228 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003229 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003230 if (flags & eAnimation) {
3231 mAnimTransactionPending = true;
3232 }
3233 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003234 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3235 if (CC_UNLIKELY(err != NO_ERROR)) {
3236 // just in case something goes wrong in SF, return to the
3237 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003238 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3239 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003240 break;
3241 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003242 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003243 }
3244}
3245
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003246uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3247 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3248 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003249
Mathias Agopiane57f2922012-08-09 16:29:12 -07003250 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003251 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3252
3253 const uint32_t what = s.what;
3254 if (what & DisplayState::eSurfaceChanged) {
3255 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3256 state.surface = s.surface;
3257 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003258 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003259 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003260 if (what & DisplayState::eLayerStackChanged) {
3261 if (state.layerStack != s.layerStack) {
3262 state.layerStack = s.layerStack;
3263 flags |= eDisplayTransactionNeeded;
3264 }
3265 }
3266 if (what & DisplayState::eDisplayProjectionChanged) {
3267 if (state.orientation != s.orientation) {
3268 state.orientation = s.orientation;
3269 flags |= eDisplayTransactionNeeded;
3270 }
3271 if (state.frame != s.frame) {
3272 state.frame = s.frame;
3273 flags |= eDisplayTransactionNeeded;
3274 }
3275 if (state.viewport != s.viewport) {
3276 state.viewport = s.viewport;
3277 flags |= eDisplayTransactionNeeded;
3278 }
3279 }
3280 if (what & DisplayState::eDisplaySizeChanged) {
3281 if (state.width != s.width) {
3282 state.width = s.width;
3283 flags |= eDisplayTransactionNeeded;
3284 }
3285 if (state.height != s.height) {
3286 state.height = s.height;
3287 flags |= eDisplayTransactionNeeded;
3288 }
3289 }
3290
Mathias Agopiane57f2922012-08-09 16:29:12 -07003291 return flags;
3292}
3293
Robert Carrd4ae7f32018-06-07 16:10:57 -07003294bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3295 IPCThreadState* ipc = IPCThreadState::self();
3296 const int pid = ipc->getCallingPid();
3297 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003298 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003299 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003300 return false;
3301 }
3302 return true;
3303}
3304
chaviwca27f252018-02-06 16:46:39 -08003305uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3306 const layer_state_t& s = composerState.state;
3307 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3308
Mathias Agopian13127d82013-03-05 17:47:11 -08003309 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003310 if (layer == nullptr) {
3311 return 0;
3312 }
3313
3314 if (layer->isPendingRemoval()) {
3315 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3316 return 0;
3317 }
3318
3319 uint32_t flags = 0;
3320
3321 const uint32_t what = s.what;
3322 bool geometryAppliesWithResize =
3323 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003324
3325 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3326 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003327 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003328 layer->pushPendingState();
3329 }
3330
chaviw8b3871a2017-11-01 17:41:01 -07003331 if (what & layer_state_t::ePositionChanged) {
3332 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3333 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003334 }
chaviw8b3871a2017-11-01 17:41:01 -07003335 }
3336 if (what & layer_state_t::eLayerChanged) {
3337 // NOTE: index needs to be calculated before we update the state
3338 const auto& p = layer->getParent();
3339 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003340 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003341 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003342 mCurrentState.layersSortedByZ.removeAt(idx);
3343 mCurrentState.layersSortedByZ.add(layer);
3344 // we need traversal (state changed)
3345 // AND transaction (list changed)
3346 flags |= eTransactionNeeded|eTraversalNeeded;
3347 }
chaviw8b3871a2017-11-01 17:41:01 -07003348 } else {
3349 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003350 flags |= eTransactionNeeded|eTraversalNeeded;
3351 }
3352 }
chaviw8b3871a2017-11-01 17:41:01 -07003353 }
3354 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003355 // NOTE: index needs to be calculated before we update the state
3356 const auto& p = layer->getParent();
3357 if (p == nullptr) {
3358 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3359 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3360 mCurrentState.layersSortedByZ.removeAt(idx);
3361 mCurrentState.layersSortedByZ.add(layer);
3362 // we need traversal (state changed)
3363 // AND transaction (list changed)
3364 flags |= eTransactionNeeded|eTraversalNeeded;
3365 }
3366 } else {
3367 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3368 flags |= eTransactionNeeded|eTraversalNeeded;
3369 }
chaviw8b3871a2017-11-01 17:41:01 -07003370 }
3371 }
3372 if (what & layer_state_t::eSizeChanged) {
3373 if (layer->setSize(s.w, s.h)) {
3374 flags |= eTraversalNeeded;
3375 }
3376 }
3377 if (what & layer_state_t::eAlphaChanged) {
3378 if (layer->setAlpha(s.alpha))
3379 flags |= eTraversalNeeded;
3380 }
3381 if (what & layer_state_t::eColorChanged) {
3382 if (layer->setColor(s.color))
3383 flags |= eTraversalNeeded;
3384 }
3385 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003386 // TODO: b/109894387
3387 //
3388 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3389 // rotation. To see the problem observe that if we have a square parent, and a child
3390 // of the same size, then we rotate the child 45 degrees around it's center, the child
3391 // must now be cropped to a non rectangular 8 sided region.
3392 //
3393 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3394 // private API, and the WindowManager only uses rotation in one case, which is on a top
3395 // level layer in which cropping is not an issue.
3396 //
3397 // However given that abuse of rotation matrices could lead to surfaces extending outside
3398 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3399 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3400 // transformations.
3401 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003402 flags |= eTraversalNeeded;
3403 }
3404 if (what & layer_state_t::eTransparentRegionChanged) {
3405 if (layer->setTransparentRegionHint(s.transparentRegion))
3406 flags |= eTraversalNeeded;
3407 }
3408 if (what & layer_state_t::eFlagsChanged) {
3409 if (layer->setFlags(s.flags, s.mask))
3410 flags |= eTraversalNeeded;
3411 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003412 if (what & layer_state_t::eCropChanged_legacy) {
3413 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003414 flags |= eTraversalNeeded;
3415 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003416 if (what & layer_state_t::eFinalCropChanged_legacy) {
3417 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003418 flags |= eTraversalNeeded;
3419 }
3420 if (what & layer_state_t::eLayerStackChanged) {
3421 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3422 // We only allow setting layer stacks for top level layers,
3423 // everything else inherits layer stack from its parent.
3424 if (layer->hasParent()) {
3425 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3426 layer->getName().string());
3427 } else if (idx < 0) {
3428 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3429 "that also does not appear in the top level layer list. Something"
3430 " has gone wrong.", layer->getName().string());
3431 } else if (layer->setLayerStack(s.layerStack)) {
3432 mCurrentState.layersSortedByZ.removeAt(idx);
3433 mCurrentState.layersSortedByZ.add(layer);
3434 // we need traversal (state changed)
3435 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003436 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003437 }
3438 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003439 if (what & layer_state_t::eDeferTransaction_legacy) {
3440 if (s.barrierHandle_legacy != nullptr) {
3441 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3442 } else if (s.barrierGbp_legacy != nullptr) {
3443 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003444 if (authenticateSurfaceTextureLocked(gbp)) {
3445 const auto& otherLayer =
3446 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003447 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003448 } else {
3449 ALOGE("Attempt to defer transaction to to an"
3450 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003451 }
3452 }
chaviw8b3871a2017-11-01 17:41:01 -07003453 // We don't trigger a traversal here because if no other state is
3454 // changed, we don't want this to cause any more work
3455 }
3456 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003457 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003458 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003459 if (!hadParent) {
3460 mCurrentState.layersSortedByZ.remove(layer);
3461 }
chaviw8b3871a2017-11-01 17:41:01 -07003462 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003463 }
chaviw8b3871a2017-11-01 17:41:01 -07003464 }
3465 if (what & layer_state_t::eReparentChildren) {
3466 if (layer->reparentChildren(s.reparentHandle)) {
3467 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003468 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003469 }
chaviw8b3871a2017-11-01 17:41:01 -07003470 if (what & layer_state_t::eDetachChildren) {
3471 layer->detachChildren();
3472 }
3473 if (what & layer_state_t::eOverrideScalingModeChanged) {
3474 layer->setOverrideScalingMode(s.overrideScalingMode);
3475 // We don't trigger a traversal here because if no other state is
3476 // changed, we don't want this to cause any more work
3477 }
Marissa Wall61c58622018-07-18 10:12:20 -07003478 if (what & layer_state_t::eTransformChanged) {
3479 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3480 }
3481 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3482 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3483 flags |= eTraversalNeeded;
3484 }
3485 if (what & layer_state_t::eCropChanged) {
3486 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3487 }
3488 if (what & layer_state_t::eBufferChanged) {
3489 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3490 }
3491 if (what & layer_state_t::eAcquireFenceChanged) {
3492 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3493 }
3494 if (what & layer_state_t::eDataspaceChanged) {
3495 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3496 }
3497 if (what & layer_state_t::eHdrMetadataChanged) {
3498 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3499 }
3500 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3501 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3502 }
3503 if (what & layer_state_t::eApiChanged) {
3504 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3505 }
3506 if (what & layer_state_t::eSidebandStreamChanged) {
3507 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3508 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003509 return flags;
3510}
3511
chaviwca27f252018-02-06 16:46:39 -08003512void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3513 const layer_state_t& state = composerState.state;
3514 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3515
3516 sp<Layer> layer(client->getLayerUser(state.surface));
3517 if (layer == nullptr) {
3518 return;
3519 }
3520
3521 if (layer->isPendingRemoval()) {
3522 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3523 return;
3524 }
3525
3526 if (state.what & layer_state_t::eDestroySurface) {
3527 removeLayerLocked(mStateLock, layer);
3528 }
3529}
3530
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003531status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003532 const String8& name,
3533 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003534 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003535 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003536 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003538 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003539 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003540 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003541 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003542 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003543
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003544 status_t result = NO_ERROR;
3545
3546 sp<Layer> layer;
3547
Cody Northropbc755282017-03-31 12:00:08 -06003548 String8 uniqueName = getUniqueLayerName(name);
3549
Mathias Agopian3165cc22012-08-08 19:42:09 -07003550 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003551 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003552 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3553 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003554
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003555 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003556 case ISurfaceComposerClient::eFXSurfaceBufferState:
3557 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3558 break;
chaviw13fdc492017-06-27 12:40:18 -07003559 case ISurfaceComposerClient::eFXSurfaceColor:
3560 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003561 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003562 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003563 break;
3564 default:
3565 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003566 break;
3567 }
3568
Dan Stoza7d89d062015-04-30 13:29:25 -07003569 if (result != NO_ERROR) {
3570 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003571 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003572
Chia-I Wuab0c3192017-08-01 11:29:00 -07003573 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3574 // TODO b/64227542
3575 if (windowType == 441731) {
3576 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3577 layer->setPrimaryDisplayOnly();
3578 }
3579
Albert Chaulk479c60c2017-01-27 14:21:34 -05003580 layer->setInfo(windowType, ownerUid);
3581
Robert Carr1f0a16a2016-10-24 16:27:39 -07003582 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003583 if (result != NO_ERROR) {
3584 return result;
3585 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003586 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003587
3588 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003589 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003590}
3591
Cody Northropbc755282017-03-31 12:00:08 -06003592String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3593{
3594 bool matchFound = true;
3595 uint32_t dupeCounter = 0;
3596
3597 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3598 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3599
Dan Stoza436ccf32018-06-21 12:10:12 -07003600 // Grab the state lock since we're accessing mCurrentState
3601 Mutex::Autolock lock(mStateLock);
3602
Cody Northropbc755282017-03-31 12:00:08 -06003603 // Loop over layers until we're sure there is no matching name
3604 while (matchFound) {
3605 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003606 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003607 if (layer->getName() == uniqueName) {
3608 matchFound = true;
3609 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3610 }
3611 });
3612 }
3613
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003614 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3615 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003616
3617 return uniqueName;
3618}
3619
Marissa Wallfd668622018-05-10 10:21:13 -07003620status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3621 uint32_t w, uint32_t h, uint32_t flags,
3622 PixelFormat& format, sp<IBinder>* handle,
3623 sp<IGraphicBufferProducer>* gbp,
3624 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003625 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003626 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003627 case PIXEL_FORMAT_TRANSPARENT:
3628 case PIXEL_FORMAT_TRANSLUCENT:
3629 format = PIXEL_FORMAT_RGBA_8888;
3630 break;
3631 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003632 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003633 break;
3634 }
3635
Marissa Wallfd668622018-05-10 10:21:13 -07003636 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3637 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003638 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003639 *handle = layer->getHandle();
3640 *gbp = layer->getProducer();
3641 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003642 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003643
Marissa Wallfd668622018-05-10 10:21:13 -07003644 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003645 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003646}
3647
Marissa Wall61c58622018-07-18 10:12:20 -07003648status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3649 uint32_t w, uint32_t h, uint32_t flags,
3650 sp<IBinder>* handle, sp<Layer>* outLayer) {
3651 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3652 *handle = layer->getHandle();
3653 *outLayer = layer;
3654
3655 return NO_ERROR;
3656}
3657
chaviw13fdc492017-06-27 12:40:18 -07003658status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003659 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003660 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003661{
chaviw13fdc492017-06-27 12:40:18 -07003662 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003663 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003664 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003665}
3666
Mathias Agopianac9fa422013-02-11 16:40:36 -08003667status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003668{
Robert Carr9524cb32017-02-13 11:32:32 -08003669 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003670 status_t err = NO_ERROR;
3671 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003672 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003673 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003674 err = removeLayer(l);
3675 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3676 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003677 }
3678 return err;
3679}
3680
Mathias Agopian13127d82013-03-05 17:47:11 -08003681status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003682{
Mathias Agopian67106042013-03-14 19:18:13 -07003683 // called by ~LayerCleaner() when all references to the IBinder (handle)
3684 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003685 sp<Layer> l = layer.promote();
3686 if (l == nullptr) {
3687 // The layer has already been removed, carry on
3688 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003689 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003690 // If we have a parent, then we can continue to live as long as it does.
3691 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003692}
3693
Mathias Agopianb60314a2012-04-10 22:09:54 -07003694// ---------------------------------------------------------------------------
3695
Andy McFadden13a082e2012-08-24 10:16:42 -07003696void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003697 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3698 if (!displayToken) return;
3699
Jesse Hall01e29052013-02-19 16:13:35 -08003700 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003701 Vector<ComposerState> state;
3702 Vector<DisplayState> displays;
3703 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003704 d.what = DisplayState::eDisplayProjectionChanged |
3705 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003706 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003707 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003708 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003709 d.frame.makeInvalid();
3710 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003711 d.width = 0;
3712 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003713 displays.add(d);
3714 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003715
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003716 const auto display = getDisplayDevice(displayToken);
3717 if (!display) return;
3718
3719 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3720
3721 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003722 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003723 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003724
Brian Andersond0010582017-03-07 13:20:31 -08003725 // Use phase of 0 since phase is not known.
3726 // Use latency of 0, which will snap to the ideal latency.
3727 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003728}
3729
3730void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003731 // Async since we may be called from the main thread.
3732 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003733}
3734
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003735void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3736 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003737 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003738 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003739
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003740 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003741 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003742 return;
3743 }
3744
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003745 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003746 ALOGW("Trying to set power mode for virtual display");
3747 return;
3748 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003749
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003750 display->setPowerMode(mode);
3751
Lloyd Pique4dccc412018-01-22 17:21:36 -08003752 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003753 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003754 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003755 if (idx < 0) {
3756 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3757 return;
3758 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003759 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003760 }
3761
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003762 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003763 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003764 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003765 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003766 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003767 // FIXME: eventthread only knows about the main display right now
3768 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003769 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003770 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003771
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003772 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003773 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003774 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003775
3776 struct sched_param param = {0};
3777 param.sched_priority = 1;
3778 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3779 ALOGW("Couldn't set SCHED_FIFO on display on");
3780 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003781 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003782 // Turn off the display
3783 struct sched_param param = {0};
3784 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3785 ALOGW("Couldn't set SCHED_OTHER on display off");
3786 }
3787
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003788 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003789 disableHardwareVsync(true); // also cancels any in-progress resync
3790
Mathias Agopiancde87a32012-09-13 14:09:01 -07003791 // FIXME: eventthread only knows about the main display right now
3792 mEventThread->onScreenReleased();
3793 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003794
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003795 getHwComposer().setPowerMode(type, mode);
3796 mVisibleRegionsDirty = true;
3797 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003798 } else if (mode == HWC_POWER_MODE_DOZE ||
3799 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003800 // Update display while dozing
3801 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003802 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003803 // FIXME: eventthread only knows about the main display right now
3804 mEventThread->onScreenAcquired();
3805 resyncToHardwareVsync(true);
3806 }
3807 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3808 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003809 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003810 disableHardwareVsync(true); // also cancels any in-progress resync
3811 // FIXME: eventthread only knows about the main display right now
3812 mEventThread->onScreenReleased();
3813 }
3814 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003815 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003816 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003817 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003818 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003819
3820 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003821}
3822
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003823void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003824 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003825 const auto display = getDisplayDevice(displayToken);
3826 if (!display) {
3827 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3828 displayToken.get());
3829 } else if (display->isVirtual()) {
3830 ALOGW("Attempt to set power mode %d for virtual display", mode);
3831 } else {
3832 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003833 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003834 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003835}
3836
3837// ---------------------------------------------------------------------------
3838
Lloyd Pique755e3192018-01-31 16:46:15 -08003839status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3840 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003841 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003842
Mathias Agopianbd115332013-04-18 16:41:04 -07003843 IPCThreadState* ipc = IPCThreadState::self();
3844 const int pid = ipc->getCallingPid();
3845 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003846
Mathias Agopianbd115332013-04-18 16:41:04 -07003847 if ((uid != AID_SHELL) &&
3848 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003849 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003850 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003851 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003852 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003853 // (this would indicate SF is stuck, but we want to be able to
3854 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003855 status_t err = mStateLock.timedLock(s2ns(1));
3856 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003857 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003858 result.appendFormat(
3859 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3860 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003861 }
3862
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003863 bool dumpAll = true;
3864 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003865 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003866
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003867 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003868 if ((index < numArgs) &&
3869 (args[index] == String16("--list"))) {
3870 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003871 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003872 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003873 }
3874
3875 if ((index < numArgs) &&
3876 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003877 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003878 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003879 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003880 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003881
3882 if ((index < numArgs) &&
3883 (args[index] == String16("--latency-clear"))) {
3884 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003885 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003886 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003887 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003888
3889 if ((index < numArgs) &&
3890 (args[index] == String16("--dispsync"))) {
3891 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003892 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003893 dumpAll = false;
3894 }
Dan Stozab90cf072015-03-05 11:05:59 -08003895
3896 if ((index < numArgs) &&
3897 (args[index] == String16("--static-screen"))) {
3898 index++;
3899 dumpStaticScreenStats(result);
3900 dumpAll = false;
3901 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003902
3903 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003904 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003905 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003906 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003907 dumpAll = false;
3908 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003909
3910 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3911 index++;
3912 dumpWideColorInfo(result);
3913 dumpAll = false;
3914 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003915
3916 if ((index < numArgs) &&
3917 (args[index] == String16("--enable-layer-stats"))) {
3918 index++;
3919 mLayerStats.enable();
3920 dumpAll = false;
3921 }
3922
3923 if ((index < numArgs) &&
3924 (args[index] == String16("--disable-layer-stats"))) {
3925 index++;
3926 mLayerStats.disable();
3927 dumpAll = false;
3928 }
3929
3930 if ((index < numArgs) &&
3931 (args[index] == String16("--clear-layer-stats"))) {
3932 index++;
3933 mLayerStats.clear();
3934 dumpAll = false;
3935 }
3936
3937 if ((index < numArgs) &&
3938 (args[index] == String16("--dump-layer-stats"))) {
3939 index++;
3940 mLayerStats.dump(result);
3941 dumpAll = false;
3942 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003943
3944 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08003945 (args[index] == String16("--frame-composition"))) {
3946 index++;
3947 dumpFrameCompositionInfo(result);
3948 dumpAll = false;
3949 }
3950
3951 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003952 (args[index] == String16("--display-identification"))) {
3953 index++;
3954 dumpDisplayIdentificationData(result);
3955 dumpAll = false;
3956 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003957
3958 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3959 index++;
3960 mTimeStats.parseArgs(asProto, args, index, result);
3961 dumpAll = false;
3962 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003963 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003964
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003965 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003966 if (asProto) {
3967 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3968 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3969 } else {
3970 dumpAllLocked(args, index, result);
3971 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003972 }
3973
Mathias Agopian9795c422009-08-26 16:36:26 -07003974 if (locked) {
3975 mStateLock.unlock();
3976 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003977 }
3978 write(fd, result.string(), result.size());
3979 return NO_ERROR;
3980}
3981
Dan Stozac7014012014-02-14 15:03:43 -08003982void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3983 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003984{
Robert Carr2047fae2016-11-28 14:09:09 -08003985 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003986 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003987 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003988}
3989
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003990void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003991 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003992{
3993 String8 name;
3994 if (index < args.size()) {
3995 name = String8(args[index]);
3996 index++;
3997 }
3998
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003999 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4000 getHwComposer().isConnected(displayId)) {
4001 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4002 const nsecs_t period = activeConfig->getVsyncPeriod();
4003 result.appendFormat("%" PRId64 "\n", period);
4004 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004005
4006 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004007 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004008 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004009 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004010 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004011 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004012 }
Robert Carr2047fae2016-11-28 14:09:09 -08004013 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004014 }
4015}
4016
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004017void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004018 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004019{
4020 String8 name;
4021 if (index < args.size()) {
4022 name = String8(args[index]);
4023 index++;
4024 }
4025
Robert Carr2047fae2016-11-28 14:09:09 -08004026 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004027 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004028 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004029 }
Robert Carr2047fae2016-11-28 14:09:09 -08004030 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004031
Svetoslavd85084b2014-03-20 10:28:31 -07004032 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004033}
4034
Jamie Gennis6547ff42013-07-16 20:12:42 -07004035// This should only be called from the main thread. Otherwise it would need
4036// the lock and should use mCurrentState rather than mDrawingState.
4037void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004038 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004039 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004040 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004041
4042 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4043}
4044
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004045void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004046{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004047 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004048
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004049 if (isLayerTripleBufferingDisabled())
4050 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004051
4052 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004053 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004054 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004055 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004056 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4057 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004058 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004059}
4060
Dan Stozab90cf072015-03-05 11:05:59 -08004061void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4062{
4063 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004064 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4065 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004066 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004067 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004068 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4069 b + 1, bucketTimeSec, percent);
4070 }
David Sodman4a36e932017-11-07 14:29:47 -08004071 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004072 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004073 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004074 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004075 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004076}
4077
Dan Stozae77c7662016-05-13 11:37:28 -07004078void SurfaceFlinger::recordBufferingStats(const char* layerName,
4079 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004080 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4081 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004082 for (const auto& segment : history) {
4083 if (!segment.usedThirdBuffer) {
4084 stats.twoBufferTime += segment.totalTime;
4085 }
4086 if (segment.occupancyAverage < 1.0f) {
4087 stats.doubleBufferedTime += segment.totalTime;
4088 } else if (segment.occupancyAverage < 2.0f) {
4089 stats.tripleBufferedTime += segment.totalTime;
4090 }
4091 ++stats.numSegments;
4092 stats.totalTime += segment.totalTime;
4093 }
4094}
4095
Brian Andersond6927fb2016-07-23 23:37:30 -07004096void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4097 result.appendFormat("Layer frame timestamps:\n");
4098
4099 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4100 const size_t count = currentLayers.size();
4101 for (size_t i=0 ; i<count ; i++) {
4102 currentLayers[i]->dumpFrameEvents(result);
4103 }
4104}
4105
Dan Stozae77c7662016-05-13 11:37:28 -07004106void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4107 result.append("Buffering stats:\n");
4108 result.append(" [Layer name] <Active time> <Two buffer> "
4109 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004110 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004111 typedef std::tuple<std::string, float, float, float> BufferTuple;
4112 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004113 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004114 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004115 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004116 if (stats.numSegments == 0) {
4117 continue;
4118 }
4119 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4120 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4121 stats.totalTime;
4122 float doubleBufferRatio = static_cast<float>(
4123 stats.doubleBufferedTime) / stats.totalTime;
4124 float tripleBufferRatio = static_cast<float>(
4125 stats.tripleBufferedTime) / stats.totalTime;
4126 sorted.insert({activeTime, {name, twoBufferRatio,
4127 doubleBufferRatio, tripleBufferRatio}});
4128 }
4129 for (const auto& sortedPair : sorted) {
4130 float activeTime = sortedPair.first;
4131 const BufferTuple& values = sortedPair.second;
4132 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4133 std::get<0>(values).c_str(), activeTime,
4134 std::get<1>(values), std::get<2>(values),
4135 std::get<3>(values));
4136 }
4137 result.append("\n");
4138}
4139
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004140void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004141 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004142 const int32_t displayId = display->getId();
4143 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4144 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004145 continue;
4146 }
4147
Dominik Laskowski7e045462018-05-30 13:02:02 -07004148 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004149 uint8_t port;
4150 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004151 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004152 result.append("no identification data\n");
4153 continue;
4154 }
4155
4156 if (!isEdid(data)) {
4157 result.append("unknown identification data: ");
4158 for (uint8_t byte : data) {
4159 result.appendFormat("%x ", byte);
4160 }
4161 result.append("\n");
4162 continue;
4163 }
4164
4165 const auto edid = parseEdid(data);
4166 if (!edid) {
4167 result.append("invalid EDID: ");
4168 for (uint8_t byte : data) {
4169 result.appendFormat("%x ", byte);
4170 }
4171 result.append("\n");
4172 continue;
4173 }
4174
4175 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4176 result.append(edid->displayName.data(), edid->displayName.length());
4177 result.append("\"\n");
4178 }
4179 result.append("\n");
4180}
4181
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004182void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004183 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4184 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004185 result.appendFormat("DisplayColorSetting: %s\n",
4186 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004187
4188 // TODO: print out if wide-color mode is active or not
4189
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004190 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004191 const int32_t displayId = display->getId();
4192 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004193 continue;
4194 }
4195
Dominik Laskowski7e045462018-05-30 13:02:02 -07004196 result.appendFormat("Display %d color modes:\n", displayId);
4197 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004198 for (auto&& mode : modes) {
4199 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4200 }
4201
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004202 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004203 result.appendFormat(" Current color mode: %s (%d)\n",
4204 decodeColorMode(currentMode).c_str(), currentMode);
4205 }
4206 result.append("\n");
4207}
4208
David Sodman7e4ae112018-02-09 15:02:28 -08004209void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4210 std::string stringResult;
4211
4212 for (const auto& [token, display] : mDisplays) {
4213 const auto displayId = display->getId();
4214 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4215 continue;
4216 }
4217
4218 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4219 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4220 break;
4221 }
4222 const auto& compositionInfoList = compositionInfoIt->second;
4223 stringResult += base::StringPrintf("Display: %d\n", displayId);
4224 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4225 for (const auto& compositionInfo : compositionInfoList) {
4226 compositionInfo.dump(stringResult, nullptr);
4227 stringResult += base::StringPrintf("\n");
4228 }
4229 }
4230
4231 result.append(stringResult.c_str());
4232}
4233
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004234LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004235 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004236 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4237 const State& state = useDrawing ? mDrawingState : mCurrentState;
4238 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004239 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004240 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004241 });
4242
4243 return layersProto;
4244}
4245
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004246LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004247 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004248
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004249 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004250 resolution->set_w(display.getWidth());
4251 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004252
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004253 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4254 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4255 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004256
Dominik Laskowski7e045462018-05-30 13:02:02 -07004257 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004258 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004259 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004260 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004261 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004262 }
4263 });
4264
4265 return layersProto;
4266}
4267
Mathias Agopian74d211a2013-04-22 16:55:35 +02004268void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4269 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004270{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004271 bool colorize = false;
4272 if (index < args.size()
4273 && (args[index] == String16("--color"))) {
4274 colorize = true;
4275 index++;
4276 }
4277
4278 Colorizer colorizer(colorize);
4279
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004280 // figure out if we're stuck somewhere
4281 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004282 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004283 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4284
4285 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004286 * Dump library configuration.
4287 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004288
4289 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004290 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004291 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004292 appendSfConfigString(result);
4293 appendUiConfigString(result);
4294 appendGuiConfigString(result);
4295 result.append("\n");
4296
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004297 result.append("\nDisplay identification data:\n");
4298 dumpDisplayIdentificationData(result);
4299
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004300 result.append("\nWide-Color information:\n");
4301 dumpWideColorInfo(result);
4302
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004303 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004304 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004305 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004306 result.append(SyncFeatures::getInstance().toString());
4307 result.append("\n");
4308
Andy McFadden41d67d72014-04-25 16:58:34 -07004309 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004310 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004311 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004312
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004313 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4314 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004315 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4316 getHwComposer().isConnected(displayId)) {
4317 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004318 result.appendFormat("Display %d: "
4319 "app phase %" PRId64 " ns, "
4320 "sf phase %" PRId64 " ns, "
4321 "early app phase %" PRId64 " ns, "
4322 "early sf phase %" PRId64 " ns, "
4323 "early app gl phase %" PRId64 " ns, "
4324 "early sf gl phase %" PRId64 " ns, "
4325 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4326 displayId,
4327 vsyncPhaseOffsetNs,
4328 sfVsyncPhaseOffsetNs,
4329 appEarlyOffset,
4330 sfEarlyOffset,
4331 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004332 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004333 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004334 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004335 result.append("\n");
4336
Dan Stozab90cf072015-03-05 11:05:59 -08004337 // Dump static screen stats
4338 result.append("\n");
4339 dumpStaticScreenStats(result);
4340 result.append("\n");
4341
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004342 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4343
Dan Stozae77c7662016-05-13 11:37:28 -07004344 dumpBufferingStats(result);
4345
Andy McFadden4803b742012-09-24 19:07:20 -07004346 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004347 * Dump the visible layer list
4348 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004349 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004350 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004351 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4352 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004353 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004354
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004355 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004356 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004357 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004358 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004359
David Sodman7e4ae112018-02-09 15:02:28 -08004360 result.append("\nFrame-Composition information:\n");
4361 dumpFrameCompositionInfo(result);
4362 result.append("\n");
4363
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004364 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004365 * Dump Display state
4366 */
4367
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004368 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004369 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004370 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004371 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004372 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004373 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004374 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004375
4376 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004377 * Dump SurfaceFlinger global state
4378 */
4379
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004380 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004381 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004382 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004383
Mathias Agopian888c8222012-08-04 21:10:38 -07004384 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004385 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004386
David Sodmanbc815282017-11-05 18:57:52 -08004387 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004388
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004389 if (display) {
4390 display->undefinedRegion.dump(result, "undefinedRegion");
4391 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4392 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004393 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004394 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004395 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004396 mTransactionFlags, !mGpuToCpuSupported);
4397
4398 if (display) {
4399 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4400 result.appendFormat(" refresh-rate : %f fps\n"
4401 " x-dpi : %f\n"
4402 " y-dpi : %f\n",
4403 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4404 activeConfig->getDpiY());
4405 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004406
Mathias Agopian74d211a2013-04-22 16:55:35 +02004407 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004408 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004409
4410 /*
4411 * VSYNC state
4412 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004413 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004414 result.append("\n");
4415
4416 /*
4417 * HWC layer minidump
4418 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004419 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004420 const int32_t displayId = display->getId();
4421 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004422 continue;
4423 }
4424
Dominik Laskowski7e045462018-05-30 13:02:02 -07004425 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004426 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004427 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004428 result.append("\n");
4429 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004430
4431 /*
4432 * Dump HWComposer state
4433 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004434 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004435 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004436 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004437 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004438 result.appendFormat(" h/w composer %s\n",
4439 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004440 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004441
4442 /*
4443 * Dump gralloc state
4444 */
4445 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4446 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004447
4448 /*
4449 * Dump VrFlinger state if in use.
4450 */
4451 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4452 result.append("VrFlinger state:\n");
4453 result.append(mVrFlinger->Dump().c_str());
4454 result.append("\n");
4455 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004456}
4457
Dominik Laskowski7e045462018-05-30 13:02:02 -07004458const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004459 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004460 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004461 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004462 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004463 }
4464 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004465
4466 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4467 static const Vector<sp<Layer>> empty;
4468 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004469}
4470
Keun young Park63f165f2012-08-31 10:53:36 -07004471bool SurfaceFlinger::startDdmConnection()
4472{
4473 void* libddmconnection_dso =
4474 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4475 if (!libddmconnection_dso) {
4476 return false;
4477 }
4478 void (*DdmConnection_start)(const char* name);
4479 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004480 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004481 if (!DdmConnection_start) {
4482 dlclose(libddmconnection_dso);
4483 return false;
4484 }
4485 (*DdmConnection_start)(getServiceName());
4486 return true;
4487}
4488
Chia-I Wu28f320b2018-05-03 11:02:56 -07004489void SurfaceFlinger::updateColorMatrixLocked() {
4490 mat4 colorMatrix;
4491 if (mGlobalSaturationFactor != 1.0f) {
4492 // Rec.709 luma coefficients
4493 float3 luminance{0.213f, 0.715f, 0.072f};
4494 luminance *= 1.0f - mGlobalSaturationFactor;
4495 mat4 saturationMatrix = mat4(
4496 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4497 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4498 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4499 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4500 );
4501 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4502 } else {
4503 colorMatrix = mClientColorMatrix * mDaltonizer();
4504 }
4505
4506 if (mCurrentState.colorMatrix != colorMatrix) {
4507 mCurrentState.colorMatrix = colorMatrix;
4508 mCurrentState.colorMatrixChanged = true;
4509 setTransactionFlags(eTransactionNeeded);
4510 }
4511}
4512
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004513status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004514#pragma clang diagnostic push
4515#pragma clang diagnostic error "-Wswitch-enum"
4516 switch (static_cast<ISurfaceComposerTag>(code)) {
4517 // These methods should at minimum make sure that the client requested
4518 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004519 case BOOT_FINISHED:
4520 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004521 case CREATE_CONNECTION:
4522 case CREATE_DISPLAY:
4523 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004524 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004525 case GET_ACTIVE_COLOR_MODE:
4526 case GET_ANIMATION_FRAME_STATS:
4527 case GET_HDR_CAPABILITIES:
4528 case SET_ACTIVE_CONFIG:
4529 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004530 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004531 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004532 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4533 IPCThreadState* ipc = IPCThreadState::self();
4534 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4535 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004536 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004537 }
Robert Carr1db73f62016-12-21 12:58:51 -08004538 return OK;
4539 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004540 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004541 IPCThreadState* ipc = IPCThreadState::self();
4542 const int pid = ipc->getCallingPid();
4543 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004544 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4545 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004546 return PERMISSION_DENIED;
4547 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004548 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004549 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004550 // Used by apps to hook Choreographer to SurfaceFlinger.
4551 case CREATE_DISPLAY_EVENT_CONNECTION:
4552 // The following calls are currently used by clients that do not
4553 // request necessary permissions. However, they do not expose any secret
4554 // information, so it is OK to pass them.
4555 case AUTHENTICATE_SURFACE:
4556 case GET_ACTIVE_CONFIG:
4557 case GET_BUILT_IN_DISPLAY:
4558 case GET_DISPLAY_COLOR_MODES:
4559 case GET_DISPLAY_CONFIGS:
4560 case GET_DISPLAY_STATS:
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -07004561 case GET_DISPLAY_VIEWPORT:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004562 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4563 // Calling setTransactionState is safe, because you need to have been
4564 // granted a reference to Client* and Handle* to do anything with it.
4565 case SET_TRANSACTION_STATE:
4566 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4567 case CREATE_SCOPED_CONNECTION: {
4568 return OK;
4569 }
4570 case CAPTURE_LAYERS:
4571 case CAPTURE_SCREEN: {
4572 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004573 IPCThreadState* ipc = IPCThreadState::self();
4574 const int pid = ipc->getCallingPid();
4575 const int uid = ipc->getCallingUid();
4576 if ((uid != AID_GRAPHICS) &&
4577 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4578 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4579 return PERMISSION_DENIED;
4580 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004581 return OK;
4582 }
4583 // The following codes are deprecated and should never be allowed to access SF.
4584 case CONNECT_DISPLAY_UNUSED:
4585 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4586 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4587 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004588 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004589 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004590
4591 // These codes are used for the IBinder protocol to either interrogate the recipient
4592 // side of the transaction for its canonical interface descriptor or to dump its state.
4593 // We let them pass by default.
4594 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4595 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4596 code == IBinder::SYSPROPS_TRANSACTION) {
4597 return OK;
4598 }
4599 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4600 // in onTransact verifies that the user is root, and has access to use SF.
4601 if (code >= 1000 && code <= 1029) {
4602 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4603 return OK;
4604 }
4605 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4606 return PERMISSION_DENIED;
4607#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004608}
4609
Ana Krulec13be8ad2018-08-21 02:43:56 +00004610status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4611 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004612 status_t credentialCheck = CheckTransactCodeCredentials(code);
4613 if (credentialCheck != OK) {
4614 return credentialCheck;
4615 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004616
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004617 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4618 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004619 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004620 IPCThreadState* ipc = IPCThreadState::self();
4621 const int uid = ipc->getCallingUid();
4622 if (CC_UNLIKELY(uid != AID_SYSTEM
4623 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004624 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004625 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004626 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004627 return PERMISSION_DENIED;
4628 }
4629 int n;
4630 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004631 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004632 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004633 return NO_ERROR;
4634 case 1002: // SHOW_UPDATES
4635 n = data.readInt32();
4636 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004637 invalidateHwcGeometry();
4638 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004639 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004640 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004641 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004642 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004643 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004644 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004645 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004646 setTransactionFlags(
4647 eTransactionNeeded|
4648 eDisplayTransactionNeeded|
4649 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004650 return NO_ERROR;
4651 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004652 case 1006:{ // send empty update
4653 signalRefresh();
4654 return NO_ERROR;
4655 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004656 case 1008: // toggle use of hw composer
4657 n = data.readInt32();
4658 mDebugDisableHWC = n ? 1 : 0;
4659 invalidateHwcGeometry();
4660 repaintEverything();
4661 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004662 case 1009: // toggle use of transform hint
4663 n = data.readInt32();
4664 mDebugDisableTransformHint = n ? 1 : 0;
4665 invalidateHwcGeometry();
4666 repaintEverything();
4667 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004668 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004669 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004670 reply->writeInt32(0);
4671 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004672 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004673 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004674 return NO_ERROR;
4675 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004676 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004677 if (!display) {
4678 return NAME_NOT_FOUND;
4679 }
4680
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004681 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004682 return NO_ERROR;
4683 }
4684 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004685 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004686 // daltonize
4687 n = data.readInt32();
4688 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004689 case 1:
4690 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4691 break;
4692 case 2:
4693 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4694 break;
4695 case 3:
4696 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4697 break;
4698 default:
4699 mDaltonizer.setType(ColorBlindnessType::None);
4700 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004701 }
4702 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004703 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004704 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004705 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004706 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004707
4708 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004709 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004710 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004711 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004712 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004713 // apply a color matrix
4714 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004715 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004716 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004717 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004718 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004719 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004720 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004721 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004722 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004723 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004724 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004725
4726 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4727 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004728 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004729 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4730 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4731 }
4732
Chia-I Wu28f320b2018-05-03 11:02:56 -07004733 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004734 return NO_ERROR;
4735 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004736 // This is an experimental interface
4737 // Needs to be shifted to proper binder interface when we productize
4738 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004739 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004740 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004741 return NO_ERROR;
4742 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004743 case 1017: {
4744 n = data.readInt32();
4745 mForceFullDamage = static_cast<bool>(n);
4746 return NO_ERROR;
4747 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004748 case 1018: { // Modify Choreographer's phase offset
4749 n = data.readInt32();
4750 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4751 return NO_ERROR;
4752 }
4753 case 1019: { // Modify SurfaceFlinger's phase offset
4754 n = data.readInt32();
4755 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4756 return NO_ERROR;
4757 }
Irvel468051e2016-06-13 16:44:44 -07004758 case 1020: { // Layer updates interceptor
4759 n = data.readInt32();
4760 if (n) {
4761 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004762 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004763 }
4764 else{
4765 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004766 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004767 }
4768 return NO_ERROR;
4769 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004770 case 1021: { // Disable HWC virtual displays
4771 n = data.readInt32();
4772 mUseHwcVirtualDisplays = !n;
4773 return NO_ERROR;
4774 }
Romain Guy0147a172017-06-01 13:53:56 -07004775 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004776 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004777 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004778
Chia-I Wu28f320b2018-05-03 11:02:56 -07004779 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004780 return NO_ERROR;
4781 }
Romain Guy54f154a2017-10-24 21:40:32 +01004782 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004783 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004784 invalidateHwcGeometry();
4785 repaintEverything();
4786 return NO_ERROR;
4787 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004788 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
4789 // deprecate 1024 if they can.
4790 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01004791 reply->writeBool(hasWideColorDisplay);
4792 return NO_ERROR;
4793 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004794 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004795 n = data.readInt32();
4796 if (n) {
4797 ALOGV("LayerTracing enabled");
4798 mTracing.enable();
4799 doTracing("tracing.enable");
4800 reply->writeInt32(NO_ERROR);
4801 } else {
4802 ALOGV("LayerTracing disabled");
4803 status_t err = mTracing.disable();
4804 reply->writeInt32(err);
4805 }
4806 return NO_ERROR;
4807 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004808 case 1026: { // Get layer tracing status
4809 reply->writeBool(mTracing.isEnabled());
4810 return NO_ERROR;
4811 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004812 // Is a DisplayColorSetting supported?
4813 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004814 const auto display = getDefaultDisplayDevice();
4815 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004816 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004817 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004818
4819 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4820 switch (setting) {
4821 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004822 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004823 break;
4824 case DisplayColorSetting::UNMANAGED:
4825 reply->writeBool(true);
4826 break;
4827 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004828 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004829 break;
4830 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004831 reply->writeBool(
4832 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004833 break;
4834 }
4835 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004836 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004837 // Is VrFlinger active?
4838 case 1028: {
4839 Mutex::Autolock _l(mStateLock);
4840 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4841 return NO_ERROR;
4842 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004843 case 1029: {
4844 // Code 1029 is an experimental feature that allows applications to
4845 // simulate a high frequency panel by setting a multiplier and divisor
4846 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07004847 // 0, then the code simply return the current multiplier and divisor.
4848 HWC2::Device::FrequencyScaler frequencyScaler;
4849 frequencyScaler.multiplier = data.readInt32();
4850 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07004851
David Sodman44b5de02018-08-21 16:28:53 -07004852 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
4853 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
4854 reply->writeInt32(frequencyScaler.multiplier);
4855 reply->writeInt32(frequencyScaler.divisor);
4856 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07004857 }
4858
David Sodman44b5de02018-08-21 16:28:53 -07004859 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07004860 enableHardwareVsync();
4861 } else {
4862 disableHardwareVsync(true);
4863 }
David Sodman44b5de02018-08-21 16:28:53 -07004864 mPrimaryDispSync->scalePeriod(frequencyScaler);
4865 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07004866
David Sodman44b5de02018-08-21 16:28:53 -07004867 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
4868 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
4869
4870 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
4871 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
4872
4873 onHotplugReceived(getBE().mComposerSequenceId,
4874 hwcDisplayId, HWC2::Connection::Disconnected);
4875 onHotplugReceived(getBE().mComposerSequenceId,
4876 hwcDisplayId, HWC2::Connection::Connected);
4877 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
4878 reply->writeInt32(frequencyScaler.multiplier);
4879 reply->writeInt32(frequencyScaler.divisor);
4880
David Sodman6d46c1e2018-07-13 12:59:48 -07004881 return NO_ERROR;
4882 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004883 // Is device color managed?
4884 case 1030: {
4885 reply->writeBool(useColorManagement);
4886 return NO_ERROR;
4887 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004888 }
4889 }
4890 return err;
4891}
4892
Steven Thomas6d8110b2017-08-31 18:24:21 -07004893void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004894 android_atomic_or(1, &mRepaintEverything);
4895 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004896}
4897
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004898// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4899class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004900public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004901 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4902 ~WindowDisconnector() {
4903 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004904 }
4905
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004906private:
4907 ANativeWindow* mWindow;
4908 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004909};
4910
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004911status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4912 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4913 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4914 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004915 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004916 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004917
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004918 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004919
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07004920 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
4921
Chia-I Wu20261cb2018-08-23 12:55:44 -07004922 sp<DisplayDevice> display;
4923 {
4924 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004925
Chia-I Wu20261cb2018-08-23 12:55:44 -07004926 display = getDisplayDeviceLocked(displayToken);
4927 if (!display) return BAD_VALUE;
4928
4929 const Rect& dispScissor = display->getScissor();
4930 if (!dispScissor.isEmpty()) {
4931 sourceCrop.set(dispScissor);
4932 // adb shell screencap will default reqWidth and reqHeight to zeros.
4933 if (reqWidth == 0 || reqHeight == 0) {
4934 reqWidth = uint32_t(display->getViewport().width());
4935 reqHeight = uint32_t(display->getViewport().height());
4936 }
4937 }
4938
4939 // get screen geometry
4940 uint32_t width = display->getWidth();
4941 uint32_t height = display->getHeight();
4942
4943 if (renderAreaRotation & ui::Transform::ROT_90) {
4944 std::swap(width, height);
4945 }
4946
4947 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4948 std::swap(width, height);
4949 }
4950
4951 if ((reqWidth > width) || (reqHeight > height)) {
4952 ALOGE("size mismatch (%d, %d) > (%d, %d)", reqWidth, reqHeight, width, height);
4953 } else {
4954 if (reqWidth == 0) {
4955 reqWidth = width;
4956 }
4957 if (reqHeight == 0) {
4958 reqHeight = height;
4959 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004960 }
4961 }
4962
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07004963 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07004964
4965 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004966 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004967 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004968}
4969
4970status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004971 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004972 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004973 ATRACE_CALL();
4974
4975 class LayerRenderArea : public RenderArea {
4976 public:
Robert Carr578038f2018-03-09 12:25:24 -08004977 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4978 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07004979 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004980 mLayer(layer),
4981 mCrop(crop),
4982 mFlinger(flinger),
4983 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004984 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004985 Rect getBounds() const override {
4986 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004987 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004988 }
Marissa Wall61c58622018-07-18 10:12:20 -07004989 int getHeight() const override {
4990 return mLayer->getActiveHeight(mLayer->getDrawingState());
4991 }
4992 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004993 bool isSecure() const override { return false; }
4994 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004995 Rect getSourceCrop() const override {
4996 if (mCrop.isEmpty()) {
4997 return getBounds();
4998 } else {
4999 return mCrop;
5000 }
5001 }
Robert Carr578038f2018-03-09 12:25:24 -08005002 class ReparentForDrawing {
5003 public:
5004 const sp<Layer>& oldParent;
5005 const sp<Layer>& newParent;
5006
5007 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5008 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005009 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005010 }
Robert Carr15eae092018-03-23 13:43:53 -07005011 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005012 };
5013
5014 void render(std::function<void()> drawLayers) override {
5015 if (!mChildrenOnly) {
5016 mTransform = mLayer->getTransform().inverse();
5017 drawLayers();
5018 } else {
5019 Rect bounds = getBounds();
5020 screenshotParentLayer =
5021 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5022 bounds.getWidth(), bounds.getHeight(), 0);
5023
5024 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5025 drawLayers();
5026 }
5027 }
chaviwa76b2712017-09-20 12:02:26 -07005028
chaviwa76b2712017-09-20 12:02:26 -07005029 private:
chaviw7206d492017-11-10 16:16:12 -08005030 const sp<Layer> mLayer;
5031 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005032
5033 // In the "childrenOnly" case we reparent the children to a screenshot
5034 // layer which has no properties set and which does not draw.
5035 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005036 ui::Transform mTransform;
Robert Carr578038f2018-03-09 12:25:24 -08005037
5038 SurfaceFlinger* mFlinger;
5039 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005040 };
5041
5042 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5043 auto parent = layerHandle->owner.promote();
5044
chaviw7206d492017-11-10 16:16:12 -08005045 if (parent == nullptr || parent->isPendingRemoval()) {
5046 ALOGE("captureLayers called with a removed parent");
5047 return NAME_NOT_FOUND;
5048 }
5049
Robert Carr578038f2018-03-09 12:25:24 -08005050 const int uid = IPCThreadState::self()->getCallingUid();
5051 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5052 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5053 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5054 return PERMISSION_DENIED;
5055 }
5056
chaviw7206d492017-11-10 16:16:12 -08005057 Rect crop(sourceCrop);
5058 if (sourceCrop.width() <= 0) {
5059 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005060 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005061 }
5062
5063 if (sourceCrop.height() <= 0) {
5064 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005065 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005066 }
5067
5068 int32_t reqWidth = crop.width() * frameScale;
5069 int32_t reqHeight = crop.height() * frameScale;
5070
Chia-I Wu20261cb2018-08-23 12:55:44 -07005071 // really small crop or frameScale
5072 if (reqWidth <= 0) {
5073 reqWidth = 1;
5074 }
5075 if (reqHeight <= 0) {
5076 reqHeight = 1;
5077 }
5078
Robert Carr578038f2018-03-09 12:25:24 -08005079 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005080
Robert Carr578038f2018-03-09 12:25:24 -08005081 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005082 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5083 if (!layer->isVisible()) {
5084 return;
Robert Carr578038f2018-03-09 12:25:24 -08005085 } else if (childrenOnly && layer == parent.get()) {
5086 return;
chaviwa76b2712017-09-20 12:02:26 -07005087 }
5088 visitor(layer);
5089 });
5090 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005091 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005092}
5093
5094status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5095 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005096 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005097 bool useIdentityTransform) {
5098 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005099
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005100 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5101 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5102 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5103 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005104
5105 // This mutex protects syncFd and captureResult for communication of the return values from the
5106 // main thread back to this Binder thread
5107 std::mutex captureMutex;
5108 std::condition_variable captureCondition;
5109 std::unique_lock<std::mutex> captureLock(captureMutex);
5110 int syncFd = -1;
5111 std::optional<status_t> captureResult;
5112
Robert Carr03480e22018-01-04 16:02:06 -08005113 const int uid = IPCThreadState::self()->getCallingUid();
5114 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5115
Dominik Laskowski8c001672018-05-30 16:52:06 -07005116 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005117 // If there is a refresh pending, bug out early and tell the binder thread to try again
5118 // after the refresh.
5119 if (mRefreshPending) {
5120 ATRACE_NAME("Skipping screenshot for now");
5121 std::unique_lock<std::mutex> captureLock(captureMutex);
5122 captureResult = std::make_optional<status_t>(EAGAIN);
5123 captureCondition.notify_one();
5124 return;
5125 }
5126
5127 status_t result = NO_ERROR;
5128 int fd = -1;
5129 {
5130 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005131 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005132 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5133 useIdentityTransform, forSystem, &fd);
5134 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005135 }
5136
5137 {
5138 std::unique_lock<std::mutex> captureLock(captureMutex);
5139 syncFd = fd;
5140 captureResult = std::make_optional<status_t>(result);
5141 captureCondition.notify_one();
5142 }
5143 });
5144
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005145 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005146 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005147 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005148 while (*captureResult == EAGAIN) {
5149 captureResult.reset();
5150 result = postMessageAsync(message);
5151 if (result != NO_ERROR) {
5152 return result;
5153 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005154 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005155 }
5156 result = *captureResult;
5157 }
5158
5159 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005160 sync_wait(syncFd, -1);
5161 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005162 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005163
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005164 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005165}
5166
chaviwa76b2712017-09-20 12:02:26 -07005167void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5168 TraverseLayersFunction traverseLayers, bool yswap,
5169 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005170 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005171
Lloyd Pique144e1162017-12-20 16:44:52 -08005172 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005173
5174 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005175 const auto raWidth = renderArea.getWidth();
5176 const auto raHeight = renderArea.getHeight();
5177
5178 const auto reqWidth = renderArea.getReqWidth();
5179 const auto reqHeight = renderArea.getReqHeight();
5180 Rect sourceCrop = renderArea.getSourceCrop();
5181
Iris Chang7501ed62018-04-30 14:45:42 +08005182 bool filtering = false;
5183 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5184 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5185 static_cast<int32_t>(reqHeight) != raWidth;
5186 } else {
5187 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5188 static_cast<int32_t>(reqHeight) != raHeight;
5189 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005190
Dan Stozac1879002014-05-22 15:59:05 -07005191 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005192 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005193 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005194 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005195 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005196 ui::Transform tr;
Iris Chang7501ed62018-04-30 14:45:42 +08005197 uint32_t flags = 0x00;
5198 switch (mPrimaryDisplayOrientation) {
5199 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005200 flags = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005201 break;
5202 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005203 flags = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005204 break;
5205 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005206 flags = ui::Transform::ROT_270;
Iris Chang7501ed62018-04-30 14:45:42 +08005207 break;
5208 }
5209 tr.set(flags, raWidth, raHeight);
5210 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005211 }
5212
5213 // ensure that sourceCrop is inside screen
5214 if (sourceCrop.left < 0) {
5215 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5216 }
chaviwa76b2712017-09-20 12:02:26 -07005217 if (sourceCrop.right > raWidth) {
5218 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005219 }
5220 if (sourceCrop.top < 0) {
5221 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5222 }
chaviwa76b2712017-09-20 12:02:26 -07005223 if (sourceCrop.bottom > raHeight) {
5224 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005225 }
5226
Chia-I Wu36574d92018-05-16 10:54:36 -07005227 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5228 engine.setOutputDataSpace(Dataspace::SRGB);
5229 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005230
Mathias Agopian180f10d2013-04-10 22:55:41 -07005231 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005232 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005233
Peiyong Linefefaac2018-08-17 12:27:51 -07005234 ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
Iris Chang7501ed62018-04-30 14:45:42 +08005235 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5236 // convert hw orientation into flag presentation
5237 // here inverse transform needed
5238 uint8_t hw_rot_90 = 0x00;
5239 uint8_t hw_flip_hv = 0x00;
5240 switch (mPrimaryDisplayOrientation) {
5241 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005242 hw_rot_90 = ui::Transform::ROT_90;
5243 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005244 break;
5245 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005246 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005247 break;
5248 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005249 hw_rot_90 = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005250 break;
5251 }
5252
5253 // transform flags operation
5254 // 1) flip H V if both have ROT_90 flag
5255 // 2) XOR these flags
Peiyong Linefefaac2018-08-17 12:27:51 -07005256 uint8_t rotation_rot_90 = rotation & ui::Transform::ROT_90;
5257 uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005258 if (rotation_rot_90 & hw_rot_90) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005259 rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005260 }
Peiyong Linefefaac2018-08-17 12:27:51 -07005261 rotation = static_cast<ui::Transform::orientation_flags>
Iris Chang7501ed62018-04-30 14:45:42 +08005262 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5263 }
5264
Mathias Agopian180f10d2013-04-10 22:55:41 -07005265 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005266 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005267 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005268 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005269
chaviw50da5042018-04-09 13:49:37 -07005270 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005271 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005272 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005273
chaviwa76b2712017-09-20 12:02:26 -07005274 traverseLayers([&](Layer* layer) {
5275 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005276 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005277 if (filtering) layer->setFiltering(false);
5278 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005279}
5280
chaviwa76b2712017-09-20 12:02:26 -07005281status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5282 TraverseLayersFunction traverseLayers,
5283 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005284 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005285 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005286 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005287 ATRACE_CALL();
5288
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005289 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005290
5291 traverseLayers([&](Layer* layer) {
5292 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5293 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005294
Robert Carr03480e22018-01-04 16:02:06 -08005295 // We allow the system server to take screenshots of secure layers for
5296 // use in situations like the Screen-rotation animation and place
5297 // the impetus on WindowManager to not persist them.
5298 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005299 ALOGW("FB is protected: PERMISSION_DENIED");
5300 return PERMISSION_DENIED;
5301 }
5302
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005303 // this binds the given EGLImage as a framebuffer for the
5304 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005305 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005306 if (bufferBond.getStatus() != NO_ERROR) {
5307 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005308 return INVALID_OPERATION;
5309 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005310
Dan Stozaabcda352017-06-01 14:37:39 -07005311 // this will in fact render into our dequeued buffer
5312 // via an FBO, which means we didn't have to create
5313 // an EGLSurface and therefore we're not
5314 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005315 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005316
Dan Stozaabcda352017-06-01 14:37:39 -07005317 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005318 getRenderEngine().finish();
5319 *outSyncFd = -1;
5320
chaviwa76b2712017-09-20 12:02:26 -07005321 const auto reqWidth = renderArea.getReqWidth();
5322 const auto reqHeight = renderArea.getReqHeight();
5323
Dan Stozaabcda352017-06-01 14:37:39 -07005324 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5325 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005326 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005327 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005328 } else {
5329 base::unique_fd syncFd = getRenderEngine().flush();
5330 if (syncFd < 0) {
5331 getRenderEngine().finish();
5332 }
5333 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005334 }
5335
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005336 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005337}
5338
Mathias Agopiand5556842013-09-19 17:08:37 -07005339void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005340 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005341 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005342 for (size_t y = 0; y < h; y++) {
5343 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5344 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005345 if (p[x] != 0xFF000000) return;
5346 }
5347 }
chaviwa76b2712017-09-20 12:02:26 -07005348 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005349
Robert Carr2047fae2016-11-28 14:09:09 -08005350 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005351 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005352 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005353 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5354 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5355 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5356 static_cast<float>(state.color.a));
5357 i++;
5358 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005359 }
5360}
5361
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005362// ---------------------------------------------------------------------------
5363
Dan Stoza412903f2017-04-27 13:42:17 -07005364void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5365 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005366}
5367
Dan Stoza412903f2017-04-27 13:42:17 -07005368void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5369 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005370}
5371
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005372void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5373 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005374 const LayerVector::Visitor& visitor) {
5375 // We loop through the first level of layers without traversing,
5376 // as we need to interpret min/max layer Z in the top level Z space.
5377 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005378 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005379 continue;
5380 }
5381 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005382 // relative layers are traversed in Layer::traverseInZOrder
5383 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005384 continue;
5385 }
5386 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005387 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005388 return;
5389 }
chaviwa76b2712017-09-20 12:02:26 -07005390 if (!layer->isVisible()) {
5391 return;
5392 }
5393 visitor(layer);
5394 });
5395 }
5396}
5397
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005398}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005399
Lloyd Pique074e8122018-07-26 12:57:23 -07005400
Mathias Agopian3f844832013-08-07 21:24:32 -07005401#if defined(__gl_h_)
5402#error "don't include gl/gl.h in this file"
5403#endif
5404
5405#if defined(__gl2_h_)
5406#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005407#endif