blob: e4b7cb4e03c9644bf4e24e8614aef575c6ee80bd [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
146#pragma clang diagnostic pop
147
Steven Thomasb02664d2017-07-26 18:48:28 -0700148class ConditionalLock {
149public:
150 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
151 if (lock) {
152 mMutex.lock();
153 }
154 }
155 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
156private:
157 Mutex& mMutex;
158 bool mLocked;
159};
Peiyong Linfca547f2018-07-09 13:03:33 -0700160
Steven Thomasb02664d2017-07-26 18:48:28 -0700161} // namespace anonymous
162
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163// ---------------------------------------------------------------------------
164
Mathias Agopian99b49842011-06-27 16:05:52 -0700165const String16 sHardwareTest("android.permission.HARDWARE_TEST");
166const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
167const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
168const String16 sDump("android.permission.DUMP");
169
170// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800171int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
172int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700173int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700174bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800175uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800176bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800177bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800178int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800179// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600180bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Lin13effd12018-07-24 17:01:47 -0700181bool SurfaceFlinger::useColorManagement;
Mathias Agopian99b49842011-06-27 16:05:52 -0700182
Kalle Raitaa099a242017-01-11 11:17:29 -0800183
184std::string getHwcServiceName() {
185 char value[PROPERTY_VALUE_MAX] = {};
186 property_get("debug.sf.hwc_service_name", value, "default");
187 ALOGI("Using HWComposer service: '%s'", value);
188 return std::string(value);
189}
190
191bool useTrebleTestingOverride() {
192 char value[PROPERTY_VALUE_MAX] = {};
193 property_get("debug.sf.treble_testing_override", value, "false");
194 ALOGI("Treble testing override: '%s'", value);
195 return std::string(value) == "true";
196}
197
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800198std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
199 switch(displayColorSetting) {
200 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700201 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800202 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700203 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800204 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700205 return std::string("Enhanced");
206 default:
207 return std::string("Unknown ") +
208 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800209 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800210}
211
Lloyd Pique99d3da52018-01-22 17:48:03 -0800212NativeWindowSurface::~NativeWindowSurface() = default;
213
214namespace impl {
215
216class NativeWindowSurface final : public android::NativeWindowSurface {
217public:
218 static std::unique_ptr<android::NativeWindowSurface> create(
219 const sp<IGraphicBufferProducer>& producer) {
220 return std::make_unique<NativeWindowSurface>(producer);
221 }
222
223 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
224 : surface(new Surface(producer, false)) {}
225
226 ~NativeWindowSurface() override = default;
227
228private:
229 sp<ANativeWindow> getNativeWindow() const override { return surface; }
230
231 void preallocateBuffers() override { surface->allocateBuffers(); }
232
233 sp<Surface> surface;
234};
235
236} // namespace impl
237
David Sodmanbc815282017-11-05 18:57:52 -0800238SurfaceFlingerBE::SurfaceFlingerBE()
239 : mHwcServiceName(getHwcServiceName()),
240 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800241 mFrameBuckets(),
242 mTotalTime(0),
243 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800244 mComposerSequenceId(0) {
245}
246
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800247SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800248 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800249 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700250 mTransactionPending(false),
251 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700252 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700253 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700254 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800255 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700256 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800258 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800259 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800260 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700262 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700263 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700264 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700265 mDebugInTransaction(0),
266 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700267 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700268 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700269 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800270 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800271 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800272 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700273 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800274 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800275 mCreateBufferQueue(&BufferQueue::createBufferQueue),
276 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800277
278SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800279 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800280
281 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
283
284 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
286
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800287 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800289
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700290 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
292
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700293 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
295
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800296 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
297 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
298
Steven Thomas050b2c82017-03-06 11:45:16 -0800299 // Vr flinger is only enabled on Daydream ready devices.
300 useVrFlinger = getBool< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::useVrFlinger>(false);
302
Fabien Sanglard1971b632017-03-10 14:50:03 -0800303 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
304 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
305
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600306 hasWideColorDisplay =
307 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700308 useColorManagement =
309 getBool<V1_2::ISurfaceFlingerConfigs, &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600310
Iris Chang7501ed62018-04-30 14:45:42 +0800311 V1_1::DisplayOrientation primaryDisplayOrientation =
312 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
313 V1_1::DisplayOrientation::ORIENTATION_0);
314
315 switch (primaryDisplayOrientation) {
316 case V1_1::DisplayOrientation::ORIENTATION_90:
317 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
318 break;
319 case V1_1::DisplayOrientation::ORIENTATION_180:
320 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
321 break;
322 case V1_1::DisplayOrientation::ORIENTATION_270:
323 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
324 break;
325 default:
326 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
327 break;
328 }
329 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
330
Lloyd Pique41be5d22018-06-21 13:11:48 -0700331 // Note: We create a local temporary with the real DispSync implementation
332 // type temporarily so we can initialize it with the configured values,
333 // before storing it for more generic use using the interface type.
334 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
335 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
336 SurfaceFlinger::dispSyncPresentTimeOffset);
337 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700338
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800339 // debugging stuff...
340 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700341
Mathias Agopianb4b17302013-03-20 18:36:41 -0700342 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700343 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700344
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800345 property_get("debug.sf.showupdates", value, "0");
346 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700347
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700348 property_get("debug.sf.ddms", value, "0");
349 mDebugDDMS = atoi(value);
350 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700351 if (!startDdmConnection()) {
352 // start failed, and DDMS debugging not enabled
353 mDebugDDMS = 0;
354 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700355 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700356 ALOGI_IF(mDebugRegion, "showupdates enabled");
357 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700358
359 property_get("debug.sf.disable_backpressure", value, "0");
360 mPropagateBackpressure = !atoi(value);
361 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700362
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800363 property_get("debug.sf.enable_hwc_vds", value, "0");
364 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800365 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800366
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800367 property_get("ro.sf.disable_triple_buffer", value, "1");
368 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800369 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700370
Yiwei Zhang243b3782018-05-15 17:40:04 -0700371 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700372 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
373 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
374
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200375 property_get("debug.sf.early_phase_offset_ns", value, "-1");
376 const int earlySfOffsetNs = atoi(value);
377
378 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
379 const int earlyGlSfOffsetNs = atoi(value);
380
381 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
382 const int earlyAppOffsetNs = atoi(value);
383
384 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
385 const int earlyGlAppOffsetNs = atoi(value);
386
387 const VSyncModulator::Offsets earlyOffsets =
388 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
389 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
390 const VSyncModulator::Offsets earlyGlOffsets =
391 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
392 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
393 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
394 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700395
Romain Guy11d63f42017-07-20 12:47:14 -0700396 // We should be reading 'persist.sys.sf.color_saturation' here
397 // but since /data may be encrypted, we need to wait until after vold
398 // comes online to attempt to read the property. The property is
399 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800400
401 if (useTrebleTestingOverride()) {
402 // Without the override SurfaceFlinger cannot connect to HIDL
403 // services that are not listed in the manifests. Considered
404 // deriving the setting from the set service name, but it
405 // would be brittle if the name that's not 'default' is used
406 // for production purposes later on.
407 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
408 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409}
410
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411void SurfaceFlinger::onFirstRef()
412{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800413 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800414}
415
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800416SurfaceFlinger::~SurfaceFlinger()
417{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800418}
419
Dan Stozac7014012014-02-14 15:03:43 -0800420void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421{
422 // the window manager died on us. prepare its eulogy.
423
Andy McFadden13a082e2012-08-24 10:16:42 -0700424 // restore initial conditions (default device unblank, etc)
425 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426
427 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700428 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429}
430
Robert Carr1db73f62016-12-21 12:58:51 -0800431static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700432 status_t err = client->initCheck();
433 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800434 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800435 }
Robert Carr1db73f62016-12-21 12:58:51 -0800436 return nullptr;
437}
438
439sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
440 return initClient(new Client(this));
441}
442
443sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
444 const sp<IGraphicBufferProducer>& gbp) {
445 if (authenticateSurfaceTexture(gbp) == false) {
446 return nullptr;
447 }
448 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
449 if (layer == nullptr) {
450 return nullptr;
451 }
452
453 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800454}
455
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700456sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
457 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700458{
459 class DisplayToken : public BBinder {
460 sp<SurfaceFlinger> flinger;
461 virtual ~DisplayToken() {
462 // no more references, this display must be terminated
463 Mutex::Autolock _l(flinger->mStateLock);
464 flinger->mCurrentState.displays.removeItem(this);
465 flinger->setTransactionFlags(eDisplayTransactionNeeded);
466 }
467 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700468 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700469 : flinger(flinger) {
470 }
471 };
472
473 sp<BBinder> token = new DisplayToken(this);
474
475 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700476 DisplayDeviceState info;
477 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700478 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700479 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700480 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800481 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700482 return token;
483}
484
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700485void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700486 Mutex::Autolock _l(mStateLock);
487
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700488 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700490 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700491 return;
492 }
493
494 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700495 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700496 ALOGE("destroyDisplay called for non-virtual display");
497 return;
498 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700499 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700500 mCurrentState.displays.removeItemsAt(idx);
501 setTransactionFlags(eDisplayTransactionNeeded);
502}
503
Mathias Agopiane57f2922012-08-09 16:29:12 -0700504sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700505 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800507 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700508 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700509 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510}
511
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800512void SurfaceFlinger::bootFinished()
513{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700514 if (mStartPropertySetThread->join() != NO_ERROR) {
515 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800516 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800517 const nsecs_t now = systemTime();
518 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000519 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700520
521 // wait patiently for the window manager death
522 const String16 name("window");
523 sp<IBinder> window(defaultServiceManager()->getService(name));
524 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700525 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700526 }
527
Steven Thomas050b2c82017-03-06 11:45:16 -0800528 if (mVrFlinger) {
529 mVrFlinger->OnBootFinished();
530 }
531
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700532 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700533 // formerly we would just kill the process, but we now ask it to exit so it
534 // can choose where to stop the animation.
535 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700536
537 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
538 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
539 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700540
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800541 postMessageAsync(new LambdaMessage([this] {
542 readPersistentProperties();
543 mBootStage = BootStage::FINISHED;
544 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800545}
546
Dan Stoza436ccf32018-06-21 12:10:12 -0700547uint32_t SurfaceFlinger::getNewTexture() {
548 {
549 std::lock_guard lock(mTexturePoolMutex);
550 if (!mTexturePool.empty()) {
551 uint32_t name = mTexturePool.back();
552 mTexturePool.pop_back();
553 ATRACE_INT("TexturePoolSize", mTexturePool.size());
554 return name;
555 }
556
557 // The pool was too small, so increase it for the future
558 ++mTexturePoolSize;
559 }
560
561 // The pool was empty, so we need to get a new texture name directly using a
562 // blocking call to the main thread
563 uint32_t name = 0;
564 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
565 return name;
566}
567
Mathias Agopian3f844832013-08-07 21:24:32 -0700568void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700569 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700570}
571
Wei Wangf9b05ee2017-07-19 20:59:39 -0700572// Do not call property_set on main thread which will be blocked by init
573// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700575 ALOGI( "SurfaceFlinger's main thread ready to run. "
576 "Initializing graphics H/W...");
577
Thierry Strudel2924d012017-08-14 15:19:37 -0700578 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900579
Steven Thomasb02664d2017-07-26 18:48:28 -0700580 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800581
Steven Thomasb02664d2017-07-26 18:48:28 -0700582 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800583 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700584 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
585 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800586 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700587 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800588 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800589 "appEventThread");
590 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700591 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800592 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800593
Lloyd Pique24b0a482018-03-09 18:52:26 -0800594 mSFEventThread =
595 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700596 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800597 [this](nsecs_t timestamp) {
598 mInterceptor->saveVSyncEvent(timestamp);
599 },
600 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800601 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200602 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800603
Steven Thomasb02664d2017-07-26 18:48:28 -0700604 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700605 int32_t renderEngineFeature = 0;
606 renderEngineFeature |= (useColorManagement ? RE::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Lloyd Pique144e1162017-12-20 16:44:52 -0800607 getBE().mRenderEngine =
Peiyong Lin13effd12018-07-24 17:01:47 -0700608 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888, renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800609 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700610
611 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
612 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800613 getBE().mHwc.reset(
614 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700615 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800616 // Process any initial hotplug and resulting display changes.
617 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700618 const auto display = getDefaultDisplayDeviceLocked();
619 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
620 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
621 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800622
Lloyd Piquefcd86612017-12-14 17:15:36 -0800623 // make the default display GLContext current so that we can create textures
624 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700625 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800626
Steven Thomas050b2c82017-03-06 11:45:16 -0800627 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700628 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700629 // This callback is called from the vr flinger dispatch thread. We
630 // need to call signalTransaction(), which requires holding
631 // mStateLock when we're not on the main thread. Acquiring
632 // mStateLock from the vr flinger dispatch thread might trigger a
633 // deadlock in surface flinger (see b/66916578), so post a message
634 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700635 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700636 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
637 mVrFlingerRequestsDisplay = requestDisplay;
638 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700639 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800640 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700641 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
642 getHwComposer()
643 .getHwcDisplayId(display->getId())
644 .value_or(0),
645 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800646 if (!mVrFlinger) {
647 ALOGE("Failed to start vrflinger");
648 }
649 }
650
Lloyd Pique379adc12018-01-22 17:31:47 -0800651 mEventControlThread = std::make_unique<impl::EventControlThread>(
652 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700653
Mathias Agopian92a979a2012-08-02 18:32:23 -0700654 // initialize our drawing state
655 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700656
Andy McFadden13a082e2012-08-24 10:16:42 -0700657 // set initial conditions (e.g. unblank default device)
658 initializeDisplays();
659
David Sodmanbc815282017-11-05 18:57:52 -0800660 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700661
Wei Wangf9b05ee2017-07-19 20:59:39 -0700662 // Inform native graphics APIs whether the present timestamp is supported:
663 if (getHwComposer().hasCapability(
664 HWC2::Capability::PresentFenceIsNotReliable)) {
665 mStartPropertySetThread = new StartPropertySetThread(false);
666 } else {
667 mStartPropertySetThread = new StartPropertySetThread(true);
668 }
669
670 if (mStartPropertySetThread->Start() != NO_ERROR) {
671 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800672 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800673
Chia-I Wud49d6692018-06-27 07:17:41 +0800674 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
675 // is used to saturate legacy sRGB content. However, to make sure the same color under
676 // Display P3 will be saturated to the same color, we intentionally break the API spec
677 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
678 // such saturation matrix on Display P3 is understood fully, the API should always return
679 // identify matrix.
680 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
681 Dataspace::SRGB_LINEAR);
682
683 // we will apply this on Display P3.
684 if (mEnhancedSaturationMatrix != mat4()) {
685 ColorSpace srgb(ColorSpace::sRGB());
686 ColorSpace displayP3(ColorSpace::DisplayP3());
687 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
688 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
689 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
690 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800691
Dan Stoza9e56aa02015-11-02 13:00:03 -0800692 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700693}
694
Romain Guy11d63f42017-07-20 12:47:14 -0700695void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700696 Mutex::Autolock _l(mStateLock);
697
Romain Guy11d63f42017-07-20 12:47:14 -0700698 char value[PROPERTY_VALUE_MAX];
699
700 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800701 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700702 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800703 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100704
705 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700706 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700707}
708
Mathias Agopiana67e4182012-06-19 17:26:12 -0700709void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800710 // Start boot animation service by setting a property mailbox
711 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700712 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800713 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700714 if (mStartPropertySetThread->join() != NO_ERROR) {
715 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800716 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700717}
718
Mathias Agopian875d8e12013-06-07 15:35:48 -0700719size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800720 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700721}
722
Mathias Agopian875d8e12013-06-07 15:35:48 -0700723size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800724 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700725}
726
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800727// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800728
Jamie Gennis582270d2011-08-17 18:19:00 -0700729bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800730 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800731 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800732 return authenticateSurfaceTextureLocked(bufferProducer);
733}
734
735bool SurfaceFlinger::authenticateSurfaceTextureLocked(
736 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800737 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800738 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800739}
740
Brian Anderson6b376712017-04-04 10:51:39 -0700741status_t SurfaceFlinger::getSupportedFrameTimestamps(
742 std::vector<FrameEvent>* outSupported) const {
743 *outSupported = {
744 FrameEvent::REQUESTED_PRESENT,
745 FrameEvent::ACQUIRE,
746 FrameEvent::LATCH,
747 FrameEvent::FIRST_REFRESH_START,
748 FrameEvent::LAST_REFRESH_START,
749 FrameEvent::GPU_COMPOSITION_DONE,
750 FrameEvent::DEQUEUE_READY,
751 FrameEvent::RELEASE,
752 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700753 ConditionalLock _l(mStateLock,
754 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700755 if (!getHwComposer().hasCapability(
756 HWC2::Capability::PresentFenceIsNotReliable)) {
757 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
758 }
759 return NO_ERROR;
760}
761
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700762status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
763 Vector<DisplayInfo>* configs) {
764 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700765 return BAD_VALUE;
766 }
767
Jesse Hall692c7232012-11-08 15:41:56 -0800768 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700769 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
770 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700771 type = i;
772 break;
773 }
774 }
775
776 if (type < 0) {
777 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700778 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700779
Mathias Agopian8b736f12012-08-13 17:54:26 -0700780 // TODO: Not sure if display density should handled by SF any longer
781 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700782 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700783 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700784 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800785 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700786 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700787 }
788 return density;
789 }
790 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700791 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700792 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700793 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700794 return getDensityFromProperty("ro.sf.lcd_density"); }
795 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700796
Dan Stoza7f7da322014-05-02 15:26:25 -0700797 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700798
Steven Thomas6d8110b2017-08-31 18:24:21 -0700799 ConditionalLock _l(mStateLock,
800 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800801 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700802 DisplayInfo info = DisplayInfo();
803
Dan Stoza9e56aa02015-11-02 13:00:03 -0800804 float xdpi = hwConfig->getDpiX();
805 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700806
807 if (type == DisplayDevice::DISPLAY_PRIMARY) {
808 // The density of the device is provided by a build property
809 float density = Density::getBuildDensity() / 160.0f;
810 if (density == 0) {
811 // the build doesn't provide a density -- this is wrong!
812 // use xdpi instead
813 ALOGE("ro.sf.lcd_density must be defined as a build property");
814 density = xdpi / 160.0f;
815 }
816 if (Density::getEmuDensity()) {
817 // if "qemu.sf.lcd_density" is specified, it overrides everything
818 xdpi = ydpi = density = Density::getEmuDensity();
819 density /= 160.0f;
820 }
821 info.density = density;
822
823 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700824 const auto display = getDefaultDisplayDeviceLocked();
825 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700826 } else {
827 // TODO: where should this value come from?
828 static const int TV_DENSITY = 213;
829 info.density = TV_DENSITY / 160.0f;
830 info.orientation = 0;
831 }
832
Dan Stoza9e56aa02015-11-02 13:00:03 -0800833 info.w = hwConfig->getWidth();
834 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 info.xdpi = xdpi;
836 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900838 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800839
Andy McFadden91b2ca82014-06-13 14:04:23 -0700840 // This is how far in advance a buffer must be queued for
841 // presentation at a given time. If you want a buffer to appear
842 // on the screen at time N, you must submit the buffer before
843 // (N - presentationDeadline).
844 //
845 // Normally it's one full refresh period (to give SF a chance to
846 // latch the buffer), but this can be reduced by configuring a
847 // DispSync offset. Any additional delays introduced by the hardware
848 // composer or panel must be accounted for here.
849 //
850 // We add an additional 1ms to allow for processing time and
851 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800852 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800853 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700854
855 // All non-virtual displays are currently considered secure.
856 info.secure = true;
857
Iris Chang7501ed62018-04-30 14:45:42 +0800858 if (type == DisplayDevice::DISPLAY_PRIMARY &&
859 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
860 std::swap(info.w, info.h);
861 }
862
Michael Wright28f24d02016-07-12 13:30:53 -0700863 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700864 }
865
Dan Stoza7f7da322014-05-02 15:26:25 -0700866 return NO_ERROR;
867}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700868
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700869status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
870 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700871 return BAD_VALUE;
872 }
873
874 // FIXME for now we always return stats for the primary display
875 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700876 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
877 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700878 return NO_ERROR;
879}
880
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -0700881status_t SurfaceFlinger::getDisplayViewport(const sp<IBinder>& display, Rect* outViewport) {
882 if (outViewport == nullptr || display.get() == nullptr) {
883 return BAD_VALUE;
884 }
885
886 sp<const DisplayDevice> device(getDisplayDevice(display));
887 if (device == nullptr) {
888 return BAD_VALUE;
889 }
890
891 *outViewport = device->getViewport();
892
893 return NO_ERROR;
894}
895
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700896int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
897 const auto display = getDisplayDevice(displayToken);
898 if (!display) {
899 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800900 return BAD_VALUE;
901 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700902
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700903 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700904}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700905
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700906void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
907 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700908 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700909 return;
910 }
911
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700912 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700913 ALOGW("Trying to set config for virtual display");
914 return;
915 }
916
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700917 display->setActiveConfig(mode);
918 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700919}
920
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700921status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700922 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700923 Vector<DisplayInfo> configs;
924 getDisplayConfigs(displayToken, &configs);
925 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
926 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
927 configs.size());
928 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700929 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700930 const auto display = getDisplayDevice(displayToken);
931 if (!display) {
932 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
933 displayToken.get());
934 } else if (display->isVirtual()) {
935 ALOGW("Attempt to set active config %d for virtual display", mode);
936 } else {
937 setActiveConfigInternal(display, mode);
938 }
939 }));
940
Mathias Agopian888c8222012-08-04 21:10:38 -0700941 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700942}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
944 Vector<ColorMode>* outColorModes) {
945 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700946 return BAD_VALUE;
947 }
948
Michael Wright28f24d02016-07-12 13:30:53 -0700949 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700950 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
951 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700952 type = i;
953 break;
954 }
955 }
956
957 if (type < 0) {
958 return type;
959 }
960
Peiyong Lina52f0292018-03-14 17:26:31 -0700961 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700962 {
963 ConditionalLock _l(mStateLock,
964 std::this_thread::get_id() != mMainThreadId);
965 modes = getHwComposer().getColorModes(type);
966 }
Michael Wright28f24d02016-07-12 13:30:53 -0700967 outColorModes->clear();
968 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
969
970 return NO_ERROR;
971}
972
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700973ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
974 if (const auto display = getDisplayDevice(displayToken)) {
975 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700976 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700977 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700978}
979
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700980void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
981 Dataspace dataSpace, RenderIntent renderIntent) {
982 ColorMode currentMode = display->getActiveColorMode();
983 Dataspace currentDataSpace = display->getCompositionDataSpace();
984 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -0700985
Peiyong Lin38e9a562018-04-10 16:24:20 -0700986 if (mode == currentMode && dataSpace == currentDataSpace &&
987 renderIntent == currentRenderIntent) {
988 return;
989 }
990
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700991 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -0700992 ALOGW("Trying to set config for virtual display");
993 return;
994 }
995
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700996 display->setActiveColorMode(mode);
997 display->setCompositionDataSpace(dataSpace);
998 display->setActiveRenderIntent(renderIntent);
999 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001000
1001 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001002 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1003 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001004}
1005
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001006status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001007 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001008 Vector<ColorMode> modes;
1009 getDisplayColorModes(displayToken, &modes);
1010 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1011 if (mode < ColorMode::NATIVE || !exists) {
1012 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1013 decodeColorMode(mode).c_str(), mode, displayToken.get());
1014 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001015 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001016 const auto display = getDisplayDevice(displayToken);
1017 if (!display) {
1018 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1019 decodeColorMode(mode).c_str(), mode, displayToken.get());
1020 } else if (display->isVirtual()) {
1021 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1022 decodeColorMode(mode).c_str(), mode);
1023 } else {
1024 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1025 RenderIntent::COLORIMETRIC);
1026 }
1027 }));
1028
Michael Wright28f24d02016-07-12 13:30:53 -07001029 return NO_ERROR;
1030}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001031
Svetoslavd85084b2014-03-20 10:28:31 -07001032status_t SurfaceFlinger::clearAnimationFrameStats() {
1033 Mutex::Autolock _l(mStateLock);
1034 mAnimFrameTracker.clearStats();
1035 return NO_ERROR;
1036}
1037
1038status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1039 Mutex::Autolock _l(mStateLock);
1040 mAnimFrameTracker.getStats(outStats);
1041 return NO_ERROR;
1042}
1043
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001044status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1045 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001046 Mutex::Autolock _l(mStateLock);
1047
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001048 const auto display = getDisplayDeviceLocked(displayToken);
1049 if (!display) {
1050 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001051 return BAD_VALUE;
1052 }
1053
Peiyong Linfb069302018-04-25 14:34:31 -07001054 // At this point the DisplayDeivce should already be set up,
1055 // meaning the luminance information is already queried from
1056 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001057 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001058 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1059 capabilities.getDesiredMaxLuminance(),
1060 capabilities.getDesiredMaxAverageLuminance(),
1061 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001062
1063 return NO_ERROR;
1064}
1065
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001066status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001067 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001068 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001069
Chia-I Wu90f669f2017-10-05 14:24:41 -07001070 if (mInjectVSyncs == enable) {
1071 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001072 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001073
1074 if (enable) {
1075 ALOGV("VSync Injections enabled");
1076 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001077 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001078 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001079 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001080 impl::EventThread::InterceptVSyncsCallback(),
1081 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001082 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001083 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001084 } else {
1085 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001086 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001087 }
1088
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001089 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001090 }));
1091
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001092 return NO_ERROR;
1093}
1094
1095status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 Mutex::Autolock _l(mStateLock);
1097
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001098 if (!mInjectVSyncs) {
1099 ALOGE("VSync Injections not enabled");
1100 return BAD_VALUE;
1101 }
1102 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1103 ALOGV("Injecting VSync inside SurfaceFlinger");
1104 mVSyncInjector->onInjectSyncEvent(when);
1105 }
1106 return NO_ERROR;
1107}
1108
Lloyd Pique755e3192018-01-31 16:46:15 -08001109status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1110 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001111 // Try to acquire a lock for 1s, fail gracefully
1112 const status_t err = mStateLock.timedLock(s2ns(1));
1113 const bool locked = (err == NO_ERROR);
1114 if (!locked) {
1115 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1116 return TIMED_OUT;
1117 }
1118
1119 outLayers->clear();
1120 mCurrentState.traverseInZOrder([&](Layer* layer) {
1121 outLayers->push_back(layer->getLayerDebugInfo());
1122 });
1123
1124 mStateLock.unlock();
1125 return NO_ERROR;
1126}
1127
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001128// ----------------------------------------------------------------------------
1129
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001130sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1131 ISurfaceComposer::VsyncSource vsyncSource) {
1132 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1133 return mSFEventThread->createEventConnection();
1134 } else {
1135 return mEventThread->createEventConnection();
1136 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001137}
1138
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001139// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001140
1141void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001142 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001143}
1144
1145void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001146 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001147}
1148
1149void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001150 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001151}
1152
1153void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001154 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001155 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001156}
1157
1158status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001159 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001160 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001161}
1162
1163status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001164 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001165 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001166 if (res == NO_ERROR) {
1167 msg->wait();
1168 }
1169 return res;
1170}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001171
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001172void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001173 do {
1174 waitForEvent();
1175 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001176}
1177
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001178void SurfaceFlinger::enableHardwareVsync() {
1179 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001180 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001181 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001182 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001183 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001184 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001185}
1186
Jesse Hall948fe0c2013-10-14 12:56:09 -07001187void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001188 Mutex::Autolock _l(mHWVsyncLock);
1189
Jesse Hall948fe0c2013-10-14 12:56:09 -07001190 if (makeAvailable) {
1191 mHWVsyncAvailable = true;
1192 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001193 // Hardware vsync is not currently available, so abort the resync
1194 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001195 return;
1196 }
1197
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001198 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1199 if (!getHwComposer().isConnected(displayId)) {
1200 return;
1201 }
1202
1203 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001204 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001205
Lloyd Pique41be5d22018-06-21 13:11:48 -07001206 mPrimaryDispSync->reset();
1207 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001208
1209 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001210 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001211 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001212 mPrimaryHWVsyncEnabled = true;
1213 }
1214}
1215
Jesse Hall948fe0c2013-10-14 12:56:09 -07001216void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001217 Mutex::Autolock _l(mHWVsyncLock);
1218 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001219 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001220 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221 mPrimaryHWVsyncEnabled = false;
1222 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001223 if (makeUnavailable) {
1224 mHWVsyncAvailable = false;
1225 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001226}
1227
Tim Murray4a4e4a22016-04-19 16:29:23 +00001228void SurfaceFlinger::resyncWithRateLimit() {
1229 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001230
1231 // No explicit locking is needed here since EventThread holds a lock while calling this method
1232 static nsecs_t sLastResyncAttempted = 0;
1233 const nsecs_t now = systemTime();
1234 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001235 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001236 }
Dan Stoza57164302017-05-08 14:03:54 -07001237 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001238}
1239
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001240void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1241 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001242 ATRACE_NAME("SF onVsync");
1243
Steven Thomas3cfac282017-02-06 12:29:30 -08001244 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001245 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001246 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001247 return;
1248 }
1249
1250 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001251 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001252 return;
1253 }
1254
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001255 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1256 // For now, we don't do anything with external display vsyncs.
1257 return;
1258 }
1259
Jamie Gennisd1700752013-10-14 12:22:52 -07001260 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261
Jamie Gennisd1700752013-10-14 12:22:52 -07001262 { // Scope for the lock
1263 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001264 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001265 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001266 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001267 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001268
1269 if (needsHwVsync) {
1270 enableHardwareVsync();
1271 } else {
1272 disableHardwareVsync(false);
1273 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001274}
1275
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001276void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001277 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1278 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001279}
1280
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001281void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001282 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001283 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001284 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001285
Lloyd Piqueba04e622017-12-14 17:11:26 -08001286 // Ignore events that do not have the right sequenceId.
1287 if (sequenceId != getBE().mComposerSequenceId) {
1288 return;
1289 }
1290
Steven Thomasb02664d2017-07-26 18:48:28 -07001291 // Only lock if we're not on the main thread. This function is normally
1292 // called on a hwbinder thread, but for the primary display it's called on
1293 // the main thread with the state lock already held, so don't attempt to
1294 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001295 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001296
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001297 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001298
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001299 if (std::this_thread::get_id() == mMainThreadId) {
1300 // Process all pending hot plug events immediately if we are on the main thread.
1301 processDisplayHotplugEventsLocked();
1302 }
1303
Lloyd Piqueba04e622017-12-14 17:11:26 -08001304 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001305}
1306
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001307void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001308 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001309 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001310 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001311 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001312 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001313}
1314
Dan Stoza9e56aa02015-11-02 13:00:03 -08001315void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001316 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001317 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001318 getHwComposer().setVsyncEnabled(disp,
1319 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001320}
1321
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001322// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001323void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001324 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001325 // Clear the drawing state so that the logic inside of
1326 // handleTransactionLocked will fire. It will determine the delta between
1327 // mCurrentState and mDrawingState and re-apply all changes when we make the
1328 // transition.
1329 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001330 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001331 mDisplays.clear();
1332}
1333
Steven Thomas050b2c82017-03-06 11:45:16 -08001334void SurfaceFlinger::updateVrFlinger() {
1335 if (!mVrFlinger)
1336 return;
1337 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001338 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001339 return;
1340 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001341
David Sodman105b7dc2017-11-04 20:28:14 -07001342 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 ALOGE("Vr flinger is only supported for remote hardware composer"
1344 " service connections. Ignoring request to transition to vr"
1345 " flinger.");
1346 mVrFlingerRequestsDisplay = false;
1347 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001348 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001349
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001350 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001351
Steven Thomas0123ac62018-07-12 11:32:34 -07001352 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001353 LOG_ALWAYS_FATAL_IF(!display);
1354 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001355 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1356 // called below. Clear the reference now so we don't accidentally use it
1357 // later.
1358 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001359
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001361 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001363
Steven Thomasb02664d2017-07-26 18:48:28 -07001364 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001365 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001366 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1367 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001368 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001369
David Sodman105b7dc2017-11-04 20:28:14 -07001370 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1371 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001372
1373 if (vrFlingerRequestsDisplay) {
1374 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001375 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001376
1377 mVisibleRegionsDirty = true;
1378 invalidateHwcGeometry();
1379
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001380 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001381 display = getDefaultDisplayDeviceLocked();
1382 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001383 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001384
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001386 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 const nsecs_t period = activeConfig->getVsyncPeriod();
1388 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001389
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001390 // The present fences returned from vr_hwc are not an accurate
1391 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001392 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1393 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001394
Steven Thomasb02664d2017-07-26 18:48:28 -07001395 // Use phase of 0 since phase is not known.
1396 // Use latency of 0, which will snap to the ideal latency.
1397 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001398
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001399 resyncToHardwareVsync(false);
1400
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001401 android_atomic_or(1, &mRepaintEverything);
1402 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001403}
1404
Mathias Agopian4fec8732012-06-29 14:12:52 -07001405void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001406 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001407 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001408 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001409 bool frameMissed = !mHadClientComposition &&
1410 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001411 (mPreviousPresentFence->getSignalTime() ==
1412 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001413 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001414 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001415 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001416 mTimeStats.incrementMissedFrames();
1417 if (mPropagateBackpressure) {
1418 signalLayerUpdate();
1419 break;
1420 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001421 }
Dan Stoza50182882016-07-08 12:02:20 -07001422
Steven Thomas050b2c82017-03-06 11:45:16 -08001423 // Now that we're going to make it to the handleMessageTransaction()
1424 // call below it's safe to call updateVrFlinger(), which will
1425 // potentially trigger a display handoff.
1426 updateVrFlinger();
1427
Dan Stoza6b9454d2014-11-07 16:00:59 -08001428 bool refreshNeeded = handleMessageTransaction();
1429 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001430 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001431 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001432 // Signal a refresh if a transaction modified the window state,
1433 // a new buffer was latched, or if HWC has requested a full
1434 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001435 signalRefresh();
1436 }
1437 break;
1438 }
1439 case MessageQueue::REFRESH: {
1440 handleMessageRefresh();
1441 break;
1442 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001443 }
1444}
1445
Dan Stoza6b9454d2014-11-07 16:00:59 -08001446bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001447 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001448 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001449 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001450 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001451 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001452 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001453}
1454
Mathias Agopian4fec8732012-06-29 14:12:52 -07001455void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001456 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001457
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001458 mRefreshPending = false;
1459
David Sodmanfa9b2af2017-12-24 13:28:59 -08001460 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001461 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001462 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001463 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001464 for (const auto& [token, display] : mDisplays) {
1465 beginFrame(display);
1466 prepareFrame(display);
1467 doDebugFlashRegions(display, repaintEverything);
1468 doComposition(display, repaintEverything);
1469 }
1470
Adrian Roos1e1a1282017-11-01 19:05:31 +01001471 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001472 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001473
1474 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001475 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001476
Dan Stozabfbffeb2016-07-21 14:49:33 -07001477 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001478 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001479 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001480 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001481 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001482
Jorim Jaggi90535212018-05-23 23:44:06 +02001483 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001484
David Sodman7e4ae112018-02-09 15:02:28 -08001485 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001486 for (const auto& [token, display] : mDisplays) {
1487 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001488 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001489 compositionInfo.hwc.hwcLayer = nullptr;
1490 }
David Sodmanba340492018-08-05 21:51:33 -07001491 }
David Sodman7e4ae112018-02-09 15:02:28 -08001492
1493 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001494}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001495
David Sodmanfa9b2af2017-12-24 13:28:59 -08001496
1497bool SurfaceFlinger::handleMessageInvalidate() {
1498 ATRACE_CALL();
1499 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001500}
1501
David Sodman79bba0e2018-08-05 18:07:49 -07001502void SurfaceFlinger::calculateWorkingSet() {
1503 ATRACE_CALL();
1504 ALOGV(__FUNCTION__);
1505
David Sodman79bba0e2018-08-05 18:07:49 -07001506 // build the h/w work list
1507 if (CC_UNLIKELY(mGeometryInvalid)) {
1508 mGeometryInvalid = false;
1509 for (const auto& [token, display] : mDisplays) {
1510 const auto displayId = display->getId();
1511 if (displayId >= 0) {
1512 const Vector<sp<Layer>>& currentLayers(
1513 display->getVisibleLayersSortedByZ());
1514 for (size_t i = 0; i < currentLayers.size(); i++) {
1515 const auto& layer = currentLayers[i];
1516
1517 if (!layer->hasHwcLayer(displayId)) {
1518 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1519 layer->forceClientComposition(displayId);
1520 continue;
1521 }
1522 }
1523
1524 layer->setGeometry(display, i);
1525 if (mDebugDisableHWC || mDebugRegion) {
1526 layer->forceClientComposition(displayId);
1527 }
1528 }
1529 }
1530 }
1531 }
1532
1533 // Set the per-frame data
1534 for (const auto& [token, display] : mDisplays) {
1535 const auto displayId = display->getId();
1536 if (displayId < 0) {
1537 continue;
1538 }
1539
1540 if (mDrawingState.colorMatrixChanged) {
1541 display->setColorTransform(mDrawingState.colorMatrix);
1542 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1543 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1544 "display %d: %d", displayId, result);
1545 }
1546 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1547 if (layer->isHdrY410()) {
1548 layer->forceClientComposition(displayId);
1549 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1550 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1551 !display->hasHDR10Support()) {
1552 layer->forceClientComposition(displayId);
1553 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1554 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1555 !display->hasHLGSupport()) {
1556 layer->forceClientComposition(displayId);
1557 }
1558
1559 if (layer->getForceClientComposition(displayId)) {
1560 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1561 layer->setCompositionType(displayId, HWC2::Composition::Client);
1562 continue;
1563 }
1564
1565 layer->setPerFrameData(display);
1566 }
1567
Peiyong Lin13effd12018-07-24 17:01:47 -07001568 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001569 ColorMode colorMode;
1570 Dataspace dataSpace;
1571 RenderIntent renderIntent;
1572 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1573 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1574 }
1575 }
1576
1577 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001578
1579 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001580 const auto displayId = display->getId();
1581 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001582 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1583 auto displayId = display->getId();
1584 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1585 if (!layer->setHwcLayer(displayId)) {
1586 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1587 }
David Sodman15fb96e2018-01-07 10:23:24 -08001588 layer->getBE().compositionInfo.hwc.displayId = displayId;
1589 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001590 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1591 }
1592 }
David Sodman79bba0e2018-08-05 18:07:49 -07001593}
1594
David Sodmanfa9b2af2017-12-24 13:28:59 -08001595void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001596{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001597 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001598 // is debugging enabled
1599 if (CC_LIKELY(!mDebugRegion))
1600 return;
1601
David Sodmanfa9b2af2017-12-24 13:28:59 -08001602 if (display->isPoweredOn()) {
1603 // transform the dirty region into this screen's coordinate space
1604 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1605 if (!dirtyRegion.isEmpty()) {
1606 // redraw the whole screen
1607 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001608
David Sodmanfa9b2af2017-12-24 13:28:59 -08001609 // and draw the dirty region
1610 const int32_t height = display->getHeight();
1611 auto& engine(getRenderEngine());
1612 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001613
David Sodmanfa9b2af2017-12-24 13:28:59 -08001614 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001615 }
1616 }
1617
David Sodmanfa9b2af2017-12-24 13:28:59 -08001618 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001619
1620 if (mDebugRegion > 1) {
1621 usleep(mDebugRegion * 1000);
1622 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001623
David Sodmanfa9b2af2017-12-24 13:28:59 -08001624 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001625 status_t result = display->prepareFrame(
1626 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001627 ALOGE_IF(result != NO_ERROR,
1628 "prepareFrame for display %d failed:"
1629 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001630 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001631 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001632}
1633
Adrian Roos1e1a1282017-11-01 19:05:31 +01001634void SurfaceFlinger::doTracing(const char* where) {
1635 ATRACE_CALL();
1636 ATRACE_NAME(where);
1637 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001638 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001639 }
1640}
1641
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001642void SurfaceFlinger::logLayerStats() {
1643 ATRACE_CALL();
1644 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001645 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001646 if (display->isPrimary()) {
1647 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001648 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001649 }
1650 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001651
1652 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001653 }
1654}
1655
David Sodman2b406362017-12-15 13:33:47 -08001656void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001657{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001658 ATRACE_CALL();
1659 ALOGV("preComposition");
1660
David Sodman2b406362017-12-15 13:33:47 -08001661 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1662
Mathias Agopiancd60f992012-08-16 16:28:27 -07001663 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001664 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001665 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001666 needExtraInvalidate = true;
1667 }
Robert Carr2047fae2016-11-28 14:09:09 -08001668 });
1669
Mathias Agopiancd60f992012-08-16 16:28:27 -07001670 if (needExtraInvalidate) {
1671 signalLayerUpdate();
1672 }
1673}
1674
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001675void SurfaceFlinger::updateCompositorTiming(
1676 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1677 std::shared_ptr<FenceTime>& presentFenceTime) {
1678 // Update queue of past composite+present times and determine the
1679 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001680 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001681 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001682 while (!getBE().mCompositePresentTimes.empty()) {
1683 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001684 // Cached values should have been updated before calling this method,
1685 // which helps avoid duplicate syscalls.
1686 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1687 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1688 break;
1689 }
1690 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001691 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001692 }
1693
1694 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001695 while (getBE().mCompositePresentTimes.size() > 16) {
1696 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001697 }
1698
Brian Andersond0010582017-03-07 13:20:31 -08001699 setCompositorTimingSnapped(
1700 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1701}
1702
1703void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1704 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001705 // Integer division and modulo round toward 0 not -inf, so we need to
1706 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001707 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001708 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1709 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1710
Brian Andersond0010582017-03-07 13:20:31 -08001711 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1712 if (idealLatency <= 0) {
1713 idealLatency = vsyncInterval;
1714 }
1715
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001716 // Snap the latency to a value that removes scheduling jitter from the
1717 // composition and present times, which often have >1ms of jitter.
1718 // Reducing jitter is important if an app attempts to extrapolate
1719 // something (such as user input) to an accurate diasplay time.
1720 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1721 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001722 nsecs_t bias = vsyncInterval / 2;
1723 int64_t extraVsyncs =
1724 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1725 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1726 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001727
David Sodman99974d22017-11-28 12:04:33 -08001728 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1729 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1730 getBE().mCompositorTiming.interval = vsyncInterval;
1731 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001732}
1733
David Sodman2b406362017-12-15 13:33:47 -08001734void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001735{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001736 ATRACE_CALL();
1737 ALOGV("postComposition");
1738
Brian Anderson3546a3f2016-07-14 11:51:14 -07001739 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001740 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001741 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001742 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001743 }
1744
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001745 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001746 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001747
David Sodman73beded2017-11-15 11:56:06 -08001748 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001749 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001750 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001751 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001752 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001753 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001754 } else {
1755 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1756 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001757
David Sodman73beded2017-11-15 11:56:06 -08001758 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001759 mPreviousPresentFence =
1760 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1761 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001762 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001763
Lloyd Pique41be5d22018-06-21 13:11:48 -07001764 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1765 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001766
David Sodman2b406362017-12-15 13:33:47 -08001767 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001768 // when we started doing work for this frame, but that should be okay
1769 // since updateCompositorTiming has snapping logic.
1770 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001771 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001772 CompositorTiming compositorTiming;
1773 {
David Sodman99974d22017-11-28 12:04:33 -08001774 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1775 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001776 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001777
Robert Carr2047fae2016-11-28 14:09:09 -08001778 mDrawingState.traverseInZOrder([&](Layer* layer) {
1779 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001780 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001781 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001782 recordBufferingStats(layer->getName().string(),
1783 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001784 }
Robert Carr2047fae2016-11-28 14:09:09 -08001785 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001786
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001787 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001788 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001789 enableHardwareVsync();
1790 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001791 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001792 }
1793 }
1794
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001795 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001796 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001797 enableHardwareVsync();
1798 }
1799 }
1800
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001801 if (mAnimCompositionPending) {
1802 mAnimCompositionPending = false;
1803
Brian Anderson4e606e32017-03-16 15:34:57 -07001804 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001805 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001806 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001807 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001808 // The HWC doesn't support present fences, so use the refresh
1809 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001810 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001811 mAnimFrameTracker.setActualPresentTime(presentTime);
1812 }
1813 mAnimFrameTracker.advanceFrame();
1814 }
Dan Stozab90cf072015-03-05 11:05:59 -08001815
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001816 mTimeStats.incrementTotalFrames();
1817 if (mHadClientComposition) {
1818 mTimeStats.incrementClientCompositionFrames();
1819 }
1820
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001821 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001822 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001823 return;
1824 }
1825
1826 nsecs_t currentTime = systemTime();
1827 if (mHasPoweredOff) {
1828 mHasPoweredOff = false;
1829 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001830 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001831 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001832 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1833 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001834 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001835 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001836 }
David Sodman4a36e932017-11-07 14:29:47 -08001837 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001838 }
David Sodman4a36e932017-11-07 14:29:47 -08001839 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001840
1841 {
1842 std::lock_guard lock(mTexturePoolMutex);
1843 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1844 if (refillCount > 0) {
1845 const size_t offset = mTexturePool.size();
1846 mTexturePool.resize(mTexturePoolSize);
1847 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1848 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1849 }
1850 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001851}
1852
1853void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001854 ATRACE_CALL();
1855 ALOGV("rebuildLayerStacks");
1856
Mathias Agopiancd60f992012-08-16 16:28:27 -07001857 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001858 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001859 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001860 mVisibleRegionsDirty = false;
1861 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001862
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001863 for (const auto& pair : mDisplays) {
1864 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001865 Region opaqueRegion;
1866 Region dirtyRegion;
1867 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001868 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001869 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001870 const Rect bounds = display->getBounds();
1871 if (display->isPoweredOn()) {
1872 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001873
Jeff Sharkey76488112017-02-27 14:15:18 -07001874 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001875 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001876 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001877 Region drawRegion(tr.transform(
1878 layer->visibleNonTransparentRegion));
1879 drawRegion.andSelf(bounds);
1880 if (!drawRegion.isEmpty()) {
1881 layersSortedByZ.add(layer);
1882 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001883 // Clear out the HWC layer if this layer was
1884 // previously visible, but no longer is
1885 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001886 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001887 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001888 // WM changes display->layerStack upon sleep/awake.
1889 // Here we make sure we delete the HWC layers even if
1890 // WM changed their layer stack.
1891 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001892 }
1893
1894 // If a layer is not going to get a release fence because
1895 // it is invisible, but it is also going to release its
1896 // old buffer, add it to the list of layers needing
1897 // fences.
1898 if (hwcLayerDestroyed) {
1899 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1900 mLayersWithQueuedFrames.cend(), layer);
1901 if (found != mLayersWithQueuedFrames.cend()) {
1902 layersNeedingFences.add(layer);
1903 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001904 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001905 });
1906 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001907 display->setVisibleLayersSortedByZ(layersSortedByZ);
1908 display->setLayersNeedingFences(layersNeedingFences);
1909 display->undefinedRegion.set(bounds);
1910 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1911 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001912 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001913 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001914}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001915
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001916// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001917// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001918// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001919// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001920// The returned HDR data space is one of
1921// - Dataspace::UNKNOWN
1922// - Dataspace::BT2020_HLG
1923// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001924Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1925 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001926 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001927 *outHdrDataSpace = Dataspace::UNKNOWN;
1928
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001929 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001930 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001931 case Dataspace::V0_SCRGB:
1932 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001933 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001934 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001935 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001936 case Dataspace::BT2020_PQ:
1937 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001938 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001939 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001940 case Dataspace::BT2020_HLG:
1941 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001942 // When there's mixed PQ content and HLG content, we set the HDR
1943 // data space to be BT2020_PQ and convert HLG to PQ.
1944 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1945 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001946 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001947 break;
1948 default:
1949 break;
1950 }
Romain Guy54f154a2017-10-24 21:40:32 +01001951 }
1952
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001953 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001954}
1955
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001956// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001957void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1958 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001959 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1960 *outMode = ColorMode::NATIVE;
1961 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001962 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001963 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001964 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001965
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001966 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001967 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001968
Peiyong Lindfde5112018-06-05 10:58:41 -07001969 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001970 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001971 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001972 if (isHdr) {
1973 bestDataSpace = hdrDataSpace;
1974 }
1975
Chia-I Wu0d711262018-05-21 15:19:35 -07001976 RenderIntent intent;
1977 switch (mDisplayColorSetting) {
1978 case DisplayColorSetting::MANAGED:
1979 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001980 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001981 break;
1982 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001983 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001984 break;
1985 default: // vendor display color setting
1986 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1987 break;
1988 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001989
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001990 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001991}
1992
David Sodmanfa9b2af2017-12-24 13:28:59 -08001993void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08001994{
David Sodmanfa9b2af2017-12-24 13:28:59 -08001995 bool dirty = !display->getDirtyRegion(false).isEmpty();
1996 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1997 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08001998
David Sodmanfa9b2af2017-12-24 13:28:59 -08001999 // If nothing has changed (!dirty), don't recompose.
2000 // If something changed, but we don't currently have any visible layers,
2001 // and didn't when we last did a composition, then skip it this time.
2002 // The second rule does two things:
2003 // - When all layers are removed from a display, we'll emit one black
2004 // frame, then nothing more until we get new layers.
2005 // - When a display is created with a private layer stack, we won't
2006 // emit any black frames until a layer is added to the layer stack.
2007 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002008
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002009 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2010 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002011 mustRecompose ? "doing" : "skipping",
2012 dirty ? "+" : "-",
2013 empty ? "+" : "-",
2014 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002015
David Sodmanfa9b2af2017-12-24 13:28:59 -08002016 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002017
David Sodmanfa9b2af2017-12-24 13:28:59 -08002018 if (mustRecompose) {
2019 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002020 }
2021}
2022
David Sodmanfa9b2af2017-12-24 13:28:59 -08002023void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002024{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002025 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002026 if (!display->isPoweredOn()) {
2027 return;
David Sodman2b406362017-12-15 13:33:47 -08002028 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002029
David Sodmanfb95bcc2017-12-22 15:45:30 -08002030 status_t result = display->prepareFrame(
2031 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002032 ALOGE_IF(result != NO_ERROR,
2033 "prepareFrame for display %d failed:"
2034 " %d (%s)",
2035 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002036}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002037
David Sodmanfa9b2af2017-12-24 13:28:59 -08002038void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002039 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002040 ALOGV("doComposition");
2041
David Sodmanfa9b2af2017-12-24 13:28:59 -08002042 if (display->isPoweredOn()) {
2043 // transform the dirty region into this screen's coordinate space
2044 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002045
David Sodmanfa9b2af2017-12-24 13:28:59 -08002046 // repaint the framebuffer (if needed)
2047 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002048
David Sodmanfa9b2af2017-12-24 13:28:59 -08002049 display->dirtyRegion.clear();
2050 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002051 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002052 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002053}
2054
David Sodmanfa9b2af2017-12-24 13:28:59 -08002055void SurfaceFlinger::postFrame()
2056{
2057 // |mStateLock| not needed as we are on the main thread
2058 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2059 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2060 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2061 logFrameStats();
2062 }
2063 }
2064}
2065
2066void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002067{
Mathias Agopian841cde52012-03-01 15:44:37 -08002068 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002069 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002070
David Sodmanfa9b2af2017-12-24 13:28:59 -08002071 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002072
David Sodmanfa9b2af2017-12-24 13:28:59 -08002073 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002074 const auto displayId = display->getId();
2075 if (displayId >= 0) {
2076 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002077 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002078 display->onSwapBuffersCompleted();
2079 display->makeCurrent();
2080 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002081 sp<Fence> releaseFence = Fence::NO_FENCE;
2082
Chia-I Wu7b549592017-11-15 09:14:57 -08002083 // The layer buffer from the previous frame (if any) is released
2084 // by HWC only when the release fence from this frame (if any) is
2085 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002086 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002087 if (displayId >= 0) {
2088 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2089 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002090
2091 // If the layer was client composited in the previous frame, we
2092 // need to merge with the previous client target acquire fence.
2093 // Since we do not track that, always merge with the current
2094 // client target acquire fence when it is available, even though
2095 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002096 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002097 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002098 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002099 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002100
David Sodmanb8af7922017-12-21 15:17:55 -08002101 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002102 }
Chia-I Wu83806892017-11-16 10:50:20 -08002103
2104 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002105 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002106 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002107 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002108 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002109 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002110 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002111 }
2112 }
2113
Dominik Laskowski7e045462018-05-30 13:02:02 -07002114 if (displayId >= 0) {
2115 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002116 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002117 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002118}
2119
Mathias Agopian87baae12012-07-31 12:38:26 -07002120void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002121{
Mathias Agopian841cde52012-03-01 15:44:37 -08002122 ATRACE_CALL();
2123
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002124 // here we keep a copy of the drawing state (that is the state that's
2125 // going to be overwritten by handleTransactionLocked()) outside of
2126 // mStateLock so that the side-effects of the State assignment
2127 // don't happen with mStateLock held (which can cause deadlocks).
2128 State drawingState(mDrawingState);
2129
Mathias Agopianca4d3602011-05-19 15:38:14 -07002130 Mutex::Autolock _l(mStateLock);
2131 const nsecs_t now = systemTime();
2132 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002133
Mathias Agopianca4d3602011-05-19 15:38:14 -07002134 // Here we're guaranteed that some transaction flags are set
2135 // so we can call handleTransactionLocked() unconditionally.
2136 // We call getTransactionFlags(), which will also clear the flags,
2137 // with mStateLock held to guarantee that mCurrentState won't change
2138 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002139
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002140 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002141 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002142 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002143
Mathias Agopianca4d3602011-05-19 15:38:14 -07002144 mLastTransactionTime = systemTime() - now;
2145 mDebugInTransaction = 0;
2146 invalidateHwcGeometry();
2147 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002148}
2149
Dominik Laskowski7e045462018-05-30 13:02:02 -07002150DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002151 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002152 // Figure out whether the event is for the primary display or an
2153 // external display by matching the Hwc display id against one for a
2154 // connected display. If we did not find a match, we then check what
2155 // displays are not already connected to determine the type. If we don't
2156 // have a connected primary display, we assume the new display is meant to
2157 // be the primary display, and then if we don't have an external display,
2158 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002159 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2160 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002161 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002162 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002163 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002164 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002165 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002166 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002167 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002168 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002169 return DisplayDevice::DISPLAY_EXTERNAL;
2170 }
2171
2172 return DisplayDevice::DISPLAY_ID_INVALID;
2173}
2174
Lloyd Piqueba04e622017-12-14 17:11:26 -08002175void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2176 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002177 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002178 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002179 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002180 continue;
2181 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002182
2183 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2184 ALOGE("External displays are not supported by the vr hardware composer.");
2185 continue;
2186 }
2187
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002188 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002189 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002190 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002191 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002192 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002193
2194 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002195 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002196 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002197 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002198 DisplayDeviceState info;
2199 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002200 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2201 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002202 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002203 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002204 mInterceptor->saveDisplayCreation(info);
2205 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002206 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002207 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002208
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002209 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002210 if (idx >= 0) {
2211 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002212 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002213 mCurrentState.displays.removeItemsAt(idx);
2214 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002215 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002216 }
2217
2218 processDisplayChangesLocked();
2219 }
2220
2221 mPendingHotplugEvents.clear();
2222}
2223
Lloyd Pique99d3da52018-01-22 17:48:03 -08002224sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002225 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002226 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002227 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002228 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002229 HdrCapabilities hdrCapabilities;
2230 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002231
Peiyong Lin13effd12018-07-24 17:01:47 -07002232 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002233 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002234 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002235 if (isWideColorMode(colorMode)) {
2236 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002237 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002238
Dominik Laskowski7e045462018-05-30 13:02:02 -07002239 std::vector<RenderIntent> renderIntents =
2240 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002241 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002242 }
tangrobin6753a022018-08-10 10:58:54 +08002243 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002244
tangrobin6753a022018-08-10 10:58:54 +08002245 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002246 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2247 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2248 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002249
2250 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2251 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2252
2253 /*
2254 * Create our display's surface
2255 */
2256 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2257 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002258 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002259 renderSurface->setNativeWindow(nativeWindow.get());
2260 const int displayWidth = renderSurface->queryWidth();
2261 const int displayHeight = renderSurface->queryHeight();
2262
2263 // Make sure that composition can never be stalled by a virtual display
2264 // consumer that isn't processing buffers fast enough. We have to do this
2265 // in two places:
2266 // * Here, in case the display is composed entirely by HWC.
2267 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2268 // window's swap interval in eglMakeCurrent, so they'll override the
2269 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002270 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002271 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2272 }
2273
2274 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002275 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002276
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002277 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002278 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2279 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2280 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002281 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002282
2283 if (maxFrameBufferAcquiredBuffers >= 3) {
2284 nativeWindowSurface->preallocateBuffers();
2285 }
2286
2287 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002288 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2289 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002290 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002291 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002292 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002293 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002294 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002295 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002296 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002297 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002298 display->setLayerStack(state.layerStack);
2299 display->setProjection(state.orientation, state.viewport, state.frame);
2300 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002301
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002302 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002303}
2304
Lloyd Pique347200f2017-12-14 17:00:15 -08002305void SurfaceFlinger::processDisplayChangesLocked() {
2306 // here we take advantage of Vector's copy-on-write semantics to
2307 // improve performance by skipping the transaction entirely when
2308 // know that the lists are identical
2309 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2310 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2311 if (!curr.isIdenticalTo(draw)) {
2312 mVisibleRegionsDirty = true;
2313 const size_t cc = curr.size();
2314 size_t dc = draw.size();
2315
2316 // find the displays that were removed
2317 // (ie: in drawing state but not in current state)
2318 // also handle displays that changed
2319 // (ie: displays that are in both lists)
2320 for (size_t i = 0; i < dc;) {
2321 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2322 if (j < 0) {
2323 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002324 // Call makeCurrent() on the primary display so we can
2325 // be sure that nothing associated with this display
2326 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002327 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2328 defaultDisplay->makeCurrent();
2329 }
2330 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2331 display->disconnect(getHwComposer());
2332 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002333 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2334 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2335 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2336 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2337 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002338 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002339 } else {
2340 // this display is in both lists. see if something changed.
2341 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002342 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002343 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2344 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2345 if (state_binder != draw_binder) {
2346 // changing the surface is like destroying and
2347 // recreating the DisplayDevice, so we just remove it
2348 // from the drawing state, so that it get re-added
2349 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002350 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2351 display->disconnect(getHwComposer());
2352 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002353 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002354 mDrawingState.displays.removeItemsAt(i);
2355 dc--;
2356 // at this point we must loop to the next item
2357 continue;
2358 }
2359
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002360 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002361 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002362 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002363 }
2364 if ((state.orientation != draw[i].orientation) ||
2365 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002366 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002367 }
2368 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002369 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002370 }
2371 }
2372 }
2373 ++i;
2374 }
2375
2376 // find displays that were added
2377 // (ie: in current state but not in drawing state)
2378 for (size_t i = 0; i < cc; i++) {
2379 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2380 const DisplayDeviceState& state(curr[i]);
2381
2382 sp<DisplaySurface> dispSurface;
2383 sp<IGraphicBufferProducer> producer;
2384 sp<IGraphicBufferProducer> bqProducer;
2385 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002386 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002387
Dominik Laskowski7e045462018-05-30 13:02:02 -07002388 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002389 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002390 // Virtual displays without a surface are dormant:
2391 // they have external state (layer stack, projection,
2392 // etc.) but no internal state (i.e. a DisplayDevice).
2393 if (state.surface != nullptr) {
2394 // Allow VR composer to use virtual displays.
2395 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2396 int width = 0;
2397 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2398 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2399 int height = 0;
2400 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2401 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2402 int intFormat = 0;
2403 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2404 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002405 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002406
Dominik Laskowski7e045462018-05-30 13:02:02 -07002407 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2408 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002409 }
2410
2411 // TODO: Plumb requested format back up to consumer
2412
2413 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002414 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002415 bqProducer, bqConsumer,
2416 state.displayName);
2417
2418 dispSurface = vds;
2419 producer = vds;
2420 }
2421 } else {
2422 ALOGE_IF(state.surface != nullptr,
2423 "adding a supported display, but rendering "
2424 "surface is provided (%p), ignoring it",
2425 state.surface.get());
2426
Dominik Laskowski7e045462018-05-30 13:02:02 -07002427 displayId = state.type;
2428 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002429 producer = bqProducer;
2430 }
2431
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002432 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002433 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002434 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002435 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002436 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002437 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002438 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2439 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2440 true);
2441 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2442 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2443 true);
2444 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002445 }
2446 }
2447 }
2448 }
2449 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002450
2451 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002452}
2453
Mathias Agopian87baae12012-07-31 12:38:26 -07002454void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002455{
Dan Stoza7dde5992015-05-22 09:51:44 -07002456 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002457 mCurrentState.traverseInZOrder([](Layer* layer) {
2458 layer->notifyAvailableFrames();
2459 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002460
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002461 /*
2462 * Traversal of the children
2463 * (perform the transaction for each of them if needed)
2464 */
2465
Mathias Agopian3559b072012-08-15 13:46:03 -07002466 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002467 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002468 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002469 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002470
2471 const uint32_t flags = layer->doTransaction(0);
2472 if (flags & Layer::eVisibleRegion)
2473 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002474 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002475 }
2476
2477 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002478 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002479 */
2480
Mathias Agopiane57f2922012-08-09 16:29:12 -07002481 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002482 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002483 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002484 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002485
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002486 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002487 // The transform hint might have changed for some layers
2488 // (either because a display has changed, or because a layer
2489 // as changed).
2490 //
2491 // Walk through all the layers in currentLayers,
2492 // and update their transform hint.
2493 //
2494 // If a layer is visible only on a single display, then that
2495 // display is used to calculate the hint, otherwise we use the
2496 // default display.
2497 //
2498 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2499 // the hint is set before we acquire a buffer from the surface texture.
2500 //
2501 // NOTE: layer transactions have taken place already, so we use their
2502 // drawing state. However, SurfaceFlinger's own transaction has not
2503 // happened yet, so we must use the current state layer list
2504 // (soon to become the drawing state list).
2505 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002506 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002507 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002508 bool first = true;
2509 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002510 // NOTE: we rely on the fact that layers are sorted by
2511 // layerStack first (so we don't have to traverse the list
2512 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002513 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002514 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002515 currentlayerStack = layerStack;
2516 // figure out if this layerstack is mirrored
2517 // (more than one display) if so, pick the default display,
2518 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002519 hintDisplay = nullptr;
2520 for (const auto& [token, display] : mDisplays) {
2521 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2522 if (hintDisplay) {
2523 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002524 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002525 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002526 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002527 }
2528 }
2529 }
2530 }
Chet Haase91d25932013-04-11 15:24:55 -07002531
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002532 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002533 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2534 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002535
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002536 // could be null when this layer is using a layerStack
2537 // that is not visible on any display. Also can occur at
2538 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002539 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002540 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002541
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002542 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002543 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002544 if (hintDisplay) {
2545 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002546 }
Robert Carr2047fae2016-11-28 14:09:09 -08002547
2548 first = false;
2549 });
Mathias Agopian84300952012-11-21 16:02:13 -08002550 }
2551
2552
Mathias Agopian3559b072012-08-15 13:46:03 -07002553 /*
2554 * Perform our own transaction if needed
2555 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002556
2557 if (mLayersAdded) {
2558 mLayersAdded = false;
2559 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002560 mVisibleRegionsDirty = true;
2561 }
2562
2563 // some layers might have been removed, so
2564 // we need to update the regions they're exposing.
2565 if (mLayersRemoved) {
2566 mLayersRemoved = false;
2567 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002568 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002569 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002570 // this layer is not visible anymore
2571 // TODO: we could traverse the tree from front to back and
2572 // compute the actual visible region
2573 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002574 Region visibleReg;
2575 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002576 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002577 }
Robert Carr2047fae2016-11-28 14:09:09 -08002578 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579 }
2580
2581 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002582
2583 updateCursorAsync();
2584}
2585
2586void SurfaceFlinger::updateCursorAsync()
2587{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002588 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002589 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002590 continue;
2591 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002592
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002593 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2594 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002595 }
2596 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002597}
2598
2599void SurfaceFlinger::commitTransaction()
2600{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002601 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002602 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002603 for (const auto& l : mLayersPendingRemoval) {
2604 recordBufferingStats(l->getName().string(),
2605 l->getOccupancyHistory(true));
2606 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002607 }
2608 mLayersPendingRemoval.clear();
2609 }
2610
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002611 // If this transaction is part of a window animation then the next frame
2612 // we composite should be considered an animation as well.
2613 mAnimCompositionPending = mAnimTransactionPending;
2614
Mathias Agopian4fec8732012-06-29 14:12:52 -07002615 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002616 // clear the "changed" flags in current state
2617 mCurrentState.colorMatrixChanged = false;
2618
Robert Carr1f0a16a2016-10-24 16:27:39 -07002619 mDrawingState.traverseInZOrder([](Layer* layer) {
2620 layer->commitChildList();
2621 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002622 mTransactionPending = false;
2623 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002624 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625}
2626
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002627void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2628 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002629 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002630 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002631
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632 Region aboveOpaqueLayers;
2633 Region aboveCoveredLayers;
2634 Region dirty;
2635
Mathias Agopian87baae12012-07-31 12:38:26 -07002636 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637
Robert Carr2047fae2016-11-28 14:09:09 -08002638 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002640 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002641
Jesse Hall01e29052013-02-19 16:13:35 -08002642 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002643 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002644 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002645 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002646
Mathias Agopianab028732010-03-16 16:41:46 -07002647 /*
2648 * opaqueRegion: area of a surface that is fully opaque.
2649 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002650 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002651
2652 /*
2653 * visibleRegion: area of a surface that is visible on screen
2654 * and not fully transparent. This is essentially the layer's
2655 * footprint minus the opaque regions above it.
2656 * Areas covered by a translucent surface are considered visible.
2657 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002659
2660 /*
2661 * coveredRegion: area of a surface that is covered by all
2662 * visible regions above it (which includes the translucent areas).
2663 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002665
Jesse Halla8026d22012-09-25 13:25:04 -07002666 /*
2667 * transparentRegion: area of a surface that is hinted to be completely
2668 * transparent. This is only used to tell when the layer has no visible
2669 * non-transparent regions and can be removed from the layer list. It
2670 * does not affect the visibleRegion of this layer or any layers
2671 * beneath it. The hint may not be correct if apps don't respect the
2672 * SurfaceView restrictions (which, sadly, some don't).
2673 */
2674 Region transparentRegion;
2675
Mathias Agopianab028732010-03-16 16:41:46 -07002676
2677 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002678 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002679 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002680 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002681 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002682 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002683 if (!visibleRegion.isEmpty()) {
2684 // Remove the transparent area from the visible region
2685 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002686 if (tr.preserveRects()) {
2687 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002688 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002689 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002690 // transformation too complex, can't do the
2691 // transparent region optimization.
2692 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002693 }
Mathias Agopianab028732010-03-16 16:41:46 -07002694 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695
Mathias Agopianab028732010-03-16 16:41:46 -07002696 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002697 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002698 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002699 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002700 // the opaque region is the layer's footprint
2701 opaqueRegion = visibleRegion;
2702 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002703 }
2704 }
2705
Robert Carre5f4f692018-01-12 13:12:28 -08002706 if (visibleRegion.isEmpty()) {
2707 layer->clearVisibilityRegions();
2708 return;
2709 }
2710
Mathias Agopianab028732010-03-16 16:41:46 -07002711 // Clip the covered region to the visible region
2712 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2713
2714 // Update aboveCoveredLayers for next (lower) layer
2715 aboveCoveredLayers.orSelf(visibleRegion);
2716
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002717 // subtract the opaque region covered by the layers above us
2718 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719
2720 // compute this layer's dirty region
2721 if (layer->contentDirty) {
2722 // we need to invalidate the whole region
2723 dirty = visibleRegion;
2724 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002725 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002726 layer->contentDirty = false;
2727 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002728 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002729 * the exposed region consists of two components:
2730 * 1) what's VISIBLE now and was COVERED before
2731 * 2) what's EXPOSED now less what was EXPOSED before
2732 *
2733 * note that (1) is conservative, we start with the whole
2734 * visible region but only keep what used to be covered by
2735 * something -- which mean it may have been exposed.
2736 *
2737 * (2) handles areas that were not covered by anything but got
2738 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002739 */
Mathias Agopianab028732010-03-16 16:41:46 -07002740 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002741 const Region oldVisibleRegion = layer->visibleRegion;
2742 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002743 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2744 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745 }
2746 dirty.subtractSelf(aboveOpaqueLayers);
2747
2748 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002749 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750
Mathias Agopianab028732010-03-16 16:41:46 -07002751 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002753
Jesse Halla8026d22012-09-25 13:25:04 -07002754 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002755 layer->setVisibleRegion(visibleRegion);
2756 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002757 layer->setVisibleNonTransparentRegion(
2758 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002759 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760
Mathias Agopian87baae12012-07-31 12:38:26 -07002761 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762}
2763
Chia-I Wuab0c3192017-08-01 11:29:00 -07002764void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002765 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002766 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2767 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002768 }
2769 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002770}
2771
Dan Stoza6b9454d2014-11-07 16:00:59 -08002772bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002774 ALOGV("handlePageFlip");
2775
Brian Andersond6927fb2016-07-23 23:37:30 -07002776 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777
Mathias Agopian4fec8732012-06-29 14:12:52 -07002778 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002779 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002780 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002781
2782 // Store the set of layers that need updates. This set must not change as
2783 // buffers are being latched, as this could result in a deadlock.
2784 // Example: Two producers share the same command stream and:
2785 // 1.) Layer 0 is latched
2786 // 2.) Layer 0 gets a new frame
2787 // 2.) Layer 1 gets a new frame
2788 // 3.) Layer 1 is latched.
2789 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2790 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002791 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002792 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002793 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002794 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002795 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002796 } else {
2797 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002798 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002799 } else {
2800 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002801 }
Robert Carr2047fae2016-11-28 14:09:09 -08002802 });
2803
Dan Stoza9e56aa02015-11-02 13:00:03 -08002804 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002805 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002806 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002807 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002808 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002809 newDataLatched = true;
2810 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002811 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002812
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002813 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002814
2815 // If we will need to wake up at some time in the future to deal with a
2816 // queued frame that shouldn't be displayed during this vsync period, wake
2817 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002818 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002819 signalLayerUpdate();
2820 }
2821
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002822 // enter boot animation on first buffer latch
2823 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2824 ALOGI("Enter boot animation");
2825 mBootStage = BootStage::BOOTANIMATION;
2826 }
2827
Dan Stoza6b9454d2014-11-07 16:00:59 -08002828 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002829 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002830}
2831
Mathias Agopianad456f92011-01-13 17:53:01 -08002832void SurfaceFlinger::invalidateHwcGeometry()
2833{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002834 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002835}
2836
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002837void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2838 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002839 // We only need to actually compose the display if:
2840 // 1) It is being handled by hardware composer, which may need this to
2841 // keep its virtual display state machine in sync, or
2842 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002843 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002844 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002846 return;
2847 }
2848
Dan Stoza9e56aa02015-11-02 13:00:03 -08002849 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002850 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002851
2852 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002853 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854}
2855
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002856bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002857 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002858
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002859 const Region bounds(display->bounds());
2860 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002861 const auto displayId = display->getId();
2862 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002863 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002864
Chia-I Wu8e50e692018-05-04 10:12:37 -07002865 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002866 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002867
Dan Stoza9e56aa02015-11-02 13:00:03 -08002868 if (hasClientComposition) {
2869 ALOGV("hasClientComposition");
2870
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002871 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002872 if (display->hasWideColorGamut()) {
2873 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002874 }
2875 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002876 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002877 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002878
Dominik Laskowski7e045462018-05-30 13:02:02 -07002879 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002880 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2881 HWC2::Capability::SkipClientColorTransform);
2882
Chia-I Wud49d6692018-06-27 07:17:41 +08002883 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002884 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2885 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002886 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002887 }
2888
Chia-I Wud49d6692018-06-27 07:17:41 +08002889 // The current enhanced saturation matrix is designed to enhance Display P3,
2890 // thus we only apply this matrix when the render intent is not colorimetric
2891 // and the output color space is Display P3.
2892 needsEnhancedColorMatrix =
2893 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2894 outputDataspace == Dataspace::DISPLAY_P3);
2895 if (needsEnhancedColorMatrix) {
2896 colorMatrix *= mEnhancedSaturationMatrix;
2897 }
2898
2899 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002900
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002901 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002902 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002903 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002904 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002905
2906 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002907 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2908 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2909 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002910 }
2911 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002912 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002913
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002914 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002915 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002916 // when using overlays, we assume a fully transparent framebuffer
2917 // NOTE: we could reduce how much we need to clear, for instance
2918 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002919 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002920 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002921 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002922 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002923 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002924 // we're left with the letterbox region
2925 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002926 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002927
2928 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002929 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002930
Mathias Agopianb9494d52012-04-18 02:28:45 -07002931 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002932 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002933 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002934 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002935 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002936 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002937
Yiwei Zhange4e26c02018-08-22 13:59:12 -07002938 const Rect& bounds = display->getBounds();
2939 const Rect& scissor = display->getScissor();
2940 if (scissor != bounds) {
2941 // scissor doesn't match the screen's dimensions, so we
2942 // need to clear everything outside of it and enable
2943 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002944
Yiwei Zhange4e26c02018-08-22 13:59:12 -07002945 // enable scissor for this frame
2946 const uint32_t height = display->getHeight();
2947 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
2948 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002949 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002950 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002951
Mathias Agopian85d751c2012-08-29 16:59:24 -07002952 /*
2953 * and then, render the layers targeted at the framebuffer
2954 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002955
Dan Stoza9e56aa02015-11-02 13:00:03 -08002956 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07002957 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002958 bool firstLayer = true;
David Sodmanfb95bcc2017-12-22 15:45:30 -08002959 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
2960 const Region bounds(display->bounds());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002961 const Region clip(bounds.intersect(
David Sodmanfb95bcc2017-12-22 15:45:30 -08002962 displayTransform.transform(compositionInfo.layer->mLayer->visibleRegion)));
2963 ALOGV("Layer: %s", compositionInfo.layerName.c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002964 if (!clip.isEmpty()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08002965 switch (compositionInfo.compositionType) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002966 case HWC2::Composition::Cursor:
2967 case HWC2::Composition::Device:
2968 case HWC2::Composition::Sideband:
2969 case HWC2::Composition::SolidColor: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08002970 const Layer::State& state(compositionInfo.layer->mLayer->getDrawingState());
2971 const bool opaque = compositionInfo.layer->mLayer->isOpaque(state);
2972 if (compositionInfo.hwc.clearClientTarget && !firstLayer &&
2973 opaque && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002974 // never clear the very first layer since we're
2975 // guaranteed the FB is already cleared
David Sodmanfb95bcc2017-12-22 15:45:30 -08002976 compositionInfo.layer->mLayer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002977 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002978 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002979 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002980 case HWC2::Composition::Client: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08002981 compositionInfo.layer->mLayer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002982 break;
2983 }
2984 default:
2985 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002986 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002987 } else {
2988 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002989 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002990 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002991 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002992
Chia-I Wud49d6692018-06-27 07:17:41 +08002993 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002994 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002995 }
2996
Mathias Agopianf45c5102012-10-24 16:29:17 -07002997 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002998 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002999 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000}
3001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003002void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3003 const Region& region) const {
3004 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003005 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003006 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003007}
3008
Dan Stoza7d89d062015-04-30 13:29:25 -07003009status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003010 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003011 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003012 const sp<Layer>& lbc,
3013 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003014{
Dan Stoza7d89d062015-04-30 13:29:25 -07003015 // add this layer to the current state list
3016 {
3017 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003018 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003019 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3020 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003021 return NO_MEMORY;
3022 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003023 if (parent == nullptr) {
3024 mCurrentState.layersSortedByZ.add(lbc);
3025 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003026 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003027 ALOGE("addClientLayer called with a removed parent");
3028 return NAME_NOT_FOUND;
3029 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003030 parent->addChild(lbc);
3031 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003032
Yiwei Zhang243b3782018-05-15 17:40:04 -07003033 if (gbc != nullptr) {
3034 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3035 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3036 mMaxGraphicBufferProducerListSize,
3037 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3038 mGraphicBufferProducerList.size(),
3039 mMaxGraphicBufferProducerListSize, mNumLayers);
3040 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003041 mLayersAdded = true;
3042 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003043 }
3044
Mathias Agopian96f08192010-06-02 23:28:45 -07003045 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003046 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003047
Dan Stoza7d89d062015-04-30 13:29:25 -07003048 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003049}
3050
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003051status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003052 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003053 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3054}
Robert Carr7f9b8992017-03-10 11:08:39 -08003055
chaviwca27f252018-02-06 16:46:39 -08003056status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3057 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003058 if (layer->isPendingRemoval()) {
3059 return NO_ERROR;
3060 }
3061
Robert Carr1f0a16a2016-10-24 16:27:39 -07003062 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003063 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003064 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003065 if (topLevelOnly) {
3066 return NO_ERROR;
3067 }
3068
Chia-I Wu98f1c102017-05-30 14:54:08 -07003069 sp<Layer> ancestor = p;
3070 while (ancestor->getParent() != nullptr) {
3071 ancestor = ancestor->getParent();
3072 }
3073 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3074 ALOGE("removeLayer called with a layer whose parent has been removed");
3075 return NAME_NOT_FOUND;
3076 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003077
3078 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003079 } else {
3080 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003081 }
3082
Robert Carr136e2f62017-02-08 17:54:29 -08003083 // As a matter of normal operation, the LayerCleaner will produce a second
3084 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3085 // so we will succeed in promoting it, but it's already been removed
3086 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3087 // otherwise something has gone wrong and we are leaking the layer.
3088 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003089 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3090 layer->getName().string(),
3091 (p != nullptr) ? p->getName().string() : "no-parent");
3092 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003093 } else if (index < 0) {
3094 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003095 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003096
Chia-I Wuc6657022017-08-15 11:18:17 -07003097 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003098 mLayersPendingRemoval.add(layer);
3099 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003100 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003101 setTransactionFlags(eTransactionNeeded);
3102 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003103}
3104
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003105uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003106 return android_atomic_release_load(&mTransactionFlags);
3107}
3108
Mathias Agopian3f844832013-08-07 21:24:32 -07003109uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3111}
3112
Mathias Agopian3f844832013-08-07 21:24:32 -07003113uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003114 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3115}
3116
3117uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3118 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003119 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003120 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003122 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003123 }
3124 return old;
3125}
3126
chaviwca27f252018-02-06 16:46:39 -08003127bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3128 for (const ComposerState& state : states) {
3129 // Here we need to check that the interface we're given is indeed
3130 // one of our own. A malicious client could give us a nullptr
3131 // IInterface, or one of its own or even one of our own but a
3132 // different type. All these situations would cause us to crash.
3133 if (state.client == nullptr) {
3134 return true;
3135 }
3136
3137 sp<IBinder> binder = IInterface::asBinder(state.client);
3138 if (binder == nullptr) {
3139 return true;
3140 }
3141
3142 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3143 return true;
3144 }
3145 }
3146 return false;
3147}
3148
Mathias Agopian8b33f032012-07-24 20:43:54 -07003149void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003150 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003151 const Vector<DisplayState>& displays,
3152 uint32_t flags)
3153{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003154 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003155 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003156 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003157
chaviwca27f252018-02-06 16:46:39 -08003158 if (containsAnyInvalidClientState(states)) {
3159 return;
3160 }
3161
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003162 if (flags & eAnimation) {
3163 // For window updates that are part of an animation we must wait for
3164 // previous animation "frames" to be handled.
3165 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003166 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003167 if (CC_UNLIKELY(err != NO_ERROR)) {
3168 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003169 // caller after a few seconds.
3170 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3171 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003172 mAnimTransactionPending = false;
3173 break;
3174 }
3175 }
3176 }
3177
chaviwca27f252018-02-06 16:46:39 -08003178 for (const DisplayState& display : displays) {
3179 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003180 }
3181
chaviwca27f252018-02-06 16:46:39 -08003182 for (const ComposerState& state : states) {
3183 transactionFlags |= setClientStateLocked(state);
3184 }
3185
3186 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3187 // as destroyed should only occur after setting all other states. This is to allow for a
3188 // child re-parent to happen before marking its original parent as destroyed (which would
3189 // then mark the child as destroyed).
3190 for (const ComposerState& state : states) {
3191 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003192 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003193
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003194 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3195 // anyway. This can be used as a flush mechanism for previous async transactions.
3196 // Empty animation transaction can be used to simulate back-pressure, so also force a
3197 // transaction for empty animation transactions.
3198 if (transactionFlags == 0 &&
3199 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003200 transactionFlags = eTransactionNeeded;
3201 }
3202
Mathias Agopian386aa982011-11-07 21:58:03 -08003203 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003204 if (mInterceptor->isEnabled()) {
3205 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003206 }
Irvel468051e2016-06-13 16:44:44 -07003207
Mathias Agopian386aa982011-11-07 21:58:03 -08003208 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003209 const auto start = (flags & eEarlyWakeup)
3210 ? VSyncModulator::TransactionStart::EARLY
3211 : VSyncModulator::TransactionStart::NORMAL;
3212 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003213
3214 // if this is a synchronous transaction, wait for it to take effect
3215 // before returning.
3216 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003217 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003218 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003219 if (flags & eAnimation) {
3220 mAnimTransactionPending = true;
3221 }
3222 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003223 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3224 if (CC_UNLIKELY(err != NO_ERROR)) {
3225 // just in case something goes wrong in SF, return to the
3226 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003227 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3228 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003229 break;
3230 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003231 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232 }
3233}
3234
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003235uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3236 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3237 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003238
Mathias Agopiane57f2922012-08-09 16:29:12 -07003239 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003240 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3241
3242 const uint32_t what = s.what;
3243 if (what & DisplayState::eSurfaceChanged) {
3244 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3245 state.surface = s.surface;
3246 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003247 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003248 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003249 if (what & DisplayState::eLayerStackChanged) {
3250 if (state.layerStack != s.layerStack) {
3251 state.layerStack = s.layerStack;
3252 flags |= eDisplayTransactionNeeded;
3253 }
3254 }
3255 if (what & DisplayState::eDisplayProjectionChanged) {
3256 if (state.orientation != s.orientation) {
3257 state.orientation = s.orientation;
3258 flags |= eDisplayTransactionNeeded;
3259 }
3260 if (state.frame != s.frame) {
3261 state.frame = s.frame;
3262 flags |= eDisplayTransactionNeeded;
3263 }
3264 if (state.viewport != s.viewport) {
3265 state.viewport = s.viewport;
3266 flags |= eDisplayTransactionNeeded;
3267 }
3268 }
3269 if (what & DisplayState::eDisplaySizeChanged) {
3270 if (state.width != s.width) {
3271 state.width = s.width;
3272 flags |= eDisplayTransactionNeeded;
3273 }
3274 if (state.height != s.height) {
3275 state.height = s.height;
3276 flags |= eDisplayTransactionNeeded;
3277 }
3278 }
3279
Mathias Agopiane57f2922012-08-09 16:29:12 -07003280 return flags;
3281}
3282
Robert Carrd4ae7f32018-06-07 16:10:57 -07003283bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3284 IPCThreadState* ipc = IPCThreadState::self();
3285 const int pid = ipc->getCallingPid();
3286 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003287 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003288 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003289 return false;
3290 }
3291 return true;
3292}
3293
chaviwca27f252018-02-06 16:46:39 -08003294uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3295 const layer_state_t& s = composerState.state;
3296 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3297
Mathias Agopian13127d82013-03-05 17:47:11 -08003298 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003299 if (layer == nullptr) {
3300 return 0;
3301 }
3302
3303 if (layer->isPendingRemoval()) {
3304 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3305 return 0;
3306 }
3307
3308 uint32_t flags = 0;
3309
3310 const uint32_t what = s.what;
3311 bool geometryAppliesWithResize =
3312 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003313
3314 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3315 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003316 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003317 layer->pushPendingState();
3318 }
3319
chaviw8b3871a2017-11-01 17:41:01 -07003320 if (what & layer_state_t::ePositionChanged) {
3321 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3322 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003323 }
chaviw8b3871a2017-11-01 17:41:01 -07003324 }
3325 if (what & layer_state_t::eLayerChanged) {
3326 // NOTE: index needs to be calculated before we update the state
3327 const auto& p = layer->getParent();
3328 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003329 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003330 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003331 mCurrentState.layersSortedByZ.removeAt(idx);
3332 mCurrentState.layersSortedByZ.add(layer);
3333 // we need traversal (state changed)
3334 // AND transaction (list changed)
3335 flags |= eTransactionNeeded|eTraversalNeeded;
3336 }
chaviw8b3871a2017-11-01 17:41:01 -07003337 } else {
3338 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003339 flags |= eTransactionNeeded|eTraversalNeeded;
3340 }
3341 }
chaviw8b3871a2017-11-01 17:41:01 -07003342 }
3343 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003344 // NOTE: index needs to be calculated before we update the state
3345 const auto& p = layer->getParent();
3346 if (p == nullptr) {
3347 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3348 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3349 mCurrentState.layersSortedByZ.removeAt(idx);
3350 mCurrentState.layersSortedByZ.add(layer);
3351 // we need traversal (state changed)
3352 // AND transaction (list changed)
3353 flags |= eTransactionNeeded|eTraversalNeeded;
3354 }
3355 } else {
3356 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3357 flags |= eTransactionNeeded|eTraversalNeeded;
3358 }
chaviw8b3871a2017-11-01 17:41:01 -07003359 }
3360 }
3361 if (what & layer_state_t::eSizeChanged) {
3362 if (layer->setSize(s.w, s.h)) {
3363 flags |= eTraversalNeeded;
3364 }
3365 }
3366 if (what & layer_state_t::eAlphaChanged) {
3367 if (layer->setAlpha(s.alpha))
3368 flags |= eTraversalNeeded;
3369 }
3370 if (what & layer_state_t::eColorChanged) {
3371 if (layer->setColor(s.color))
3372 flags |= eTraversalNeeded;
3373 }
3374 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003375 // TODO: b/109894387
3376 //
3377 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3378 // rotation. To see the problem observe that if we have a square parent, and a child
3379 // of the same size, then we rotate the child 45 degrees around it's center, the child
3380 // must now be cropped to a non rectangular 8 sided region.
3381 //
3382 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3383 // private API, and the WindowManager only uses rotation in one case, which is on a top
3384 // level layer in which cropping is not an issue.
3385 //
3386 // However given that abuse of rotation matrices could lead to surfaces extending outside
3387 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3388 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3389 // transformations.
3390 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003391 flags |= eTraversalNeeded;
3392 }
3393 if (what & layer_state_t::eTransparentRegionChanged) {
3394 if (layer->setTransparentRegionHint(s.transparentRegion))
3395 flags |= eTraversalNeeded;
3396 }
3397 if (what & layer_state_t::eFlagsChanged) {
3398 if (layer->setFlags(s.flags, s.mask))
3399 flags |= eTraversalNeeded;
3400 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003401 if (what & layer_state_t::eCropChanged_legacy) {
3402 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003403 flags |= eTraversalNeeded;
3404 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003405 if (what & layer_state_t::eFinalCropChanged_legacy) {
3406 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003407 flags |= eTraversalNeeded;
3408 }
3409 if (what & layer_state_t::eLayerStackChanged) {
3410 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3411 // We only allow setting layer stacks for top level layers,
3412 // everything else inherits layer stack from its parent.
3413 if (layer->hasParent()) {
3414 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3415 layer->getName().string());
3416 } else if (idx < 0) {
3417 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3418 "that also does not appear in the top level layer list. Something"
3419 " has gone wrong.", layer->getName().string());
3420 } else if (layer->setLayerStack(s.layerStack)) {
3421 mCurrentState.layersSortedByZ.removeAt(idx);
3422 mCurrentState.layersSortedByZ.add(layer);
3423 // we need traversal (state changed)
3424 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003425 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003426 }
3427 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003428 if (what & layer_state_t::eDeferTransaction_legacy) {
3429 if (s.barrierHandle_legacy != nullptr) {
3430 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3431 } else if (s.barrierGbp_legacy != nullptr) {
3432 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003433 if (authenticateSurfaceTextureLocked(gbp)) {
3434 const auto& otherLayer =
3435 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003436 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003437 } else {
3438 ALOGE("Attempt to defer transaction to to an"
3439 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003440 }
3441 }
chaviw8b3871a2017-11-01 17:41:01 -07003442 // We don't trigger a traversal here because if no other state is
3443 // changed, we don't want this to cause any more work
3444 }
3445 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003446 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003447 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003448 if (!hadParent) {
3449 mCurrentState.layersSortedByZ.remove(layer);
3450 }
chaviw8b3871a2017-11-01 17:41:01 -07003451 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003452 }
chaviw8b3871a2017-11-01 17:41:01 -07003453 }
3454 if (what & layer_state_t::eReparentChildren) {
3455 if (layer->reparentChildren(s.reparentHandle)) {
3456 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003457 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003458 }
chaviw8b3871a2017-11-01 17:41:01 -07003459 if (what & layer_state_t::eDetachChildren) {
3460 layer->detachChildren();
3461 }
3462 if (what & layer_state_t::eOverrideScalingModeChanged) {
3463 layer->setOverrideScalingMode(s.overrideScalingMode);
3464 // We don't trigger a traversal here because if no other state is
3465 // changed, we don't want this to cause any more work
3466 }
Marissa Wall61c58622018-07-18 10:12:20 -07003467 if (what & layer_state_t::eTransformChanged) {
3468 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3469 }
3470 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3471 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3472 flags |= eTraversalNeeded;
3473 }
3474 if (what & layer_state_t::eCropChanged) {
3475 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3476 }
3477 if (what & layer_state_t::eBufferChanged) {
3478 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3479 }
3480 if (what & layer_state_t::eAcquireFenceChanged) {
3481 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3482 }
3483 if (what & layer_state_t::eDataspaceChanged) {
3484 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3485 }
3486 if (what & layer_state_t::eHdrMetadataChanged) {
3487 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3488 }
3489 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3490 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3491 }
3492 if (what & layer_state_t::eApiChanged) {
3493 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3494 }
3495 if (what & layer_state_t::eSidebandStreamChanged) {
3496 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3497 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003498 return flags;
3499}
3500
chaviwca27f252018-02-06 16:46:39 -08003501void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3502 const layer_state_t& state = composerState.state;
3503 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3504
3505 sp<Layer> layer(client->getLayerUser(state.surface));
3506 if (layer == nullptr) {
3507 return;
3508 }
3509
3510 if (layer->isPendingRemoval()) {
3511 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3512 return;
3513 }
3514
3515 if (state.what & layer_state_t::eDestroySurface) {
3516 removeLayerLocked(mStateLock, layer);
3517 }
3518}
3519
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003520status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003521 const String8& name,
3522 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003523 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003524 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003525 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003526{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003527 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003528 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003529 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003530 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003531 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003532
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003533 status_t result = NO_ERROR;
3534
3535 sp<Layer> layer;
3536
Cody Northropbc755282017-03-31 12:00:08 -06003537 String8 uniqueName = getUniqueLayerName(name);
3538
Mathias Agopian3165cc22012-08-08 19:42:09 -07003539 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003540 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003541 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3542 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003543
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003544 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003545 case ISurfaceComposerClient::eFXSurfaceBufferState:
3546 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3547 break;
chaviw13fdc492017-06-27 12:40:18 -07003548 case ISurfaceComposerClient::eFXSurfaceColor:
3549 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003550 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003551 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003552 break;
3553 default:
3554 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003555 break;
3556 }
3557
Dan Stoza7d89d062015-04-30 13:29:25 -07003558 if (result != NO_ERROR) {
3559 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003560 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003561
Chia-I Wuab0c3192017-08-01 11:29:00 -07003562 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3563 // TODO b/64227542
3564 if (windowType == 441731) {
3565 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3566 layer->setPrimaryDisplayOnly();
3567 }
3568
Albert Chaulk479c60c2017-01-27 14:21:34 -05003569 layer->setInfo(windowType, ownerUid);
3570
Robert Carr1f0a16a2016-10-24 16:27:39 -07003571 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003572 if (result != NO_ERROR) {
3573 return result;
3574 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003575 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003576
3577 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003578 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579}
3580
Cody Northropbc755282017-03-31 12:00:08 -06003581String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3582{
3583 bool matchFound = true;
3584 uint32_t dupeCounter = 0;
3585
3586 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3587 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3588
Dan Stoza436ccf32018-06-21 12:10:12 -07003589 // Grab the state lock since we're accessing mCurrentState
3590 Mutex::Autolock lock(mStateLock);
3591
Cody Northropbc755282017-03-31 12:00:08 -06003592 // Loop over layers until we're sure there is no matching name
3593 while (matchFound) {
3594 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003595 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003596 if (layer->getName() == uniqueName) {
3597 matchFound = true;
3598 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3599 }
3600 });
3601 }
3602
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003603 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3604 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003605
3606 return uniqueName;
3607}
3608
Marissa Wallfd668622018-05-10 10:21:13 -07003609status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3610 uint32_t w, uint32_t h, uint32_t flags,
3611 PixelFormat& format, sp<IBinder>* handle,
3612 sp<IGraphicBufferProducer>* gbp,
3613 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003614 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003615 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003616 case PIXEL_FORMAT_TRANSPARENT:
3617 case PIXEL_FORMAT_TRANSLUCENT:
3618 format = PIXEL_FORMAT_RGBA_8888;
3619 break;
3620 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003621 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003622 break;
3623 }
3624
Marissa Wallfd668622018-05-10 10:21:13 -07003625 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3626 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003627 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003628 *handle = layer->getHandle();
3629 *gbp = layer->getProducer();
3630 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003631 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003632
Marissa Wallfd668622018-05-10 10:21:13 -07003633 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003634 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003635}
3636
Marissa Wall61c58622018-07-18 10:12:20 -07003637status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3638 uint32_t w, uint32_t h, uint32_t flags,
3639 sp<IBinder>* handle, sp<Layer>* outLayer) {
3640 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3641 *handle = layer->getHandle();
3642 *outLayer = layer;
3643
3644 return NO_ERROR;
3645}
3646
chaviw13fdc492017-06-27 12:40:18 -07003647status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003648 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003649 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003650{
chaviw13fdc492017-06-27 12:40:18 -07003651 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003652 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003653 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003654}
3655
Mathias Agopianac9fa422013-02-11 16:40:36 -08003656status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003657{
Robert Carr9524cb32017-02-13 11:32:32 -08003658 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003659 status_t err = NO_ERROR;
3660 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003661 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003662 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003663 err = removeLayer(l);
3664 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3665 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003666 }
3667 return err;
3668}
3669
Mathias Agopian13127d82013-03-05 17:47:11 -08003670status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003671{
Mathias Agopian67106042013-03-14 19:18:13 -07003672 // called by ~LayerCleaner() when all references to the IBinder (handle)
3673 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003674 sp<Layer> l = layer.promote();
3675 if (l == nullptr) {
3676 // The layer has already been removed, carry on
3677 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003678 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003679 // If we have a parent, then we can continue to live as long as it does.
3680 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003681}
3682
Mathias Agopianb60314a2012-04-10 22:09:54 -07003683// ---------------------------------------------------------------------------
3684
Andy McFadden13a082e2012-08-24 10:16:42 -07003685void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003686 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3687 if (!displayToken) return;
3688
Jesse Hall01e29052013-02-19 16:13:35 -08003689 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003690 Vector<ComposerState> state;
3691 Vector<DisplayState> displays;
3692 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003693 d.what = DisplayState::eDisplayProjectionChanged |
3694 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003695 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003696 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003697 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003698 d.frame.makeInvalid();
3699 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003700 d.width = 0;
3701 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003702 displays.add(d);
3703 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003704
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003705 const auto display = getDisplayDevice(displayToken);
3706 if (!display) return;
3707
3708 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3709
3710 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003711 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003712 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003713
Brian Andersond0010582017-03-07 13:20:31 -08003714 // Use phase of 0 since phase is not known.
3715 // Use latency of 0, which will snap to the ideal latency.
3716 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003717}
3718
3719void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003720 // Async since we may be called from the main thread.
3721 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003722}
3723
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003724void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3725 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003726 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003727 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003728
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003729 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003730 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003731 return;
3732 }
3733
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003734 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003735 ALOGW("Trying to set power mode for virtual display");
3736 return;
3737 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003738
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003739 display->setPowerMode(mode);
3740
Lloyd Pique4dccc412018-01-22 17:21:36 -08003741 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003742 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003743 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003744 if (idx < 0) {
3745 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3746 return;
3747 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003748 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003749 }
3750
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003751 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003752 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003753 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003754 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003755 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003756 // FIXME: eventthread only knows about the main display right now
3757 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003758 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003759 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003760
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003761 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003762 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003763 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003764
3765 struct sched_param param = {0};
3766 param.sched_priority = 1;
3767 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3768 ALOGW("Couldn't set SCHED_FIFO on display on");
3769 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003770 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003771 // Turn off the display
3772 struct sched_param param = {0};
3773 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3774 ALOGW("Couldn't set SCHED_OTHER on display off");
3775 }
3776
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003777 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003778 disableHardwareVsync(true); // also cancels any in-progress resync
3779
Mathias Agopiancde87a32012-09-13 14:09:01 -07003780 // FIXME: eventthread only knows about the main display right now
3781 mEventThread->onScreenReleased();
3782 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003783
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003784 getHwComposer().setPowerMode(type, mode);
3785 mVisibleRegionsDirty = true;
3786 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003787 } else if (mode == HWC_POWER_MODE_DOZE ||
3788 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003789 // Update display while dozing
3790 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003791 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003792 // FIXME: eventthread only knows about the main display right now
3793 mEventThread->onScreenAcquired();
3794 resyncToHardwareVsync(true);
3795 }
3796 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3797 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003798 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003799 disableHardwareVsync(true); // also cancels any in-progress resync
3800 // FIXME: eventthread only knows about the main display right now
3801 mEventThread->onScreenReleased();
3802 }
3803 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003804 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003805 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003806 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003807 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003808
3809 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003810}
3811
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003812void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003813 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003814 const auto display = getDisplayDevice(displayToken);
3815 if (!display) {
3816 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3817 displayToken.get());
3818 } else if (display->isVirtual()) {
3819 ALOGW("Attempt to set power mode %d for virtual display", mode);
3820 } else {
3821 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003822 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003823 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003824}
3825
3826// ---------------------------------------------------------------------------
3827
Lloyd Pique755e3192018-01-31 16:46:15 -08003828status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3829 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003830 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003831
Mathias Agopianbd115332013-04-18 16:41:04 -07003832 IPCThreadState* ipc = IPCThreadState::self();
3833 const int pid = ipc->getCallingPid();
3834 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003835
Mathias Agopianbd115332013-04-18 16:41:04 -07003836 if ((uid != AID_SHELL) &&
3837 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003838 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003839 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003840 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003841 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003842 // (this would indicate SF is stuck, but we want to be able to
3843 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003844 status_t err = mStateLock.timedLock(s2ns(1));
3845 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003846 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003847 result.appendFormat(
3848 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3849 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003850 }
3851
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003852 bool dumpAll = true;
3853 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003854 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003855
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003856 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003857 if ((index < numArgs) &&
3858 (args[index] == String16("--list"))) {
3859 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003860 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003861 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003862 }
3863
3864 if ((index < numArgs) &&
3865 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003866 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003867 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003868 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003869 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003870
3871 if ((index < numArgs) &&
3872 (args[index] == String16("--latency-clear"))) {
3873 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003874 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003875 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003876 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003877
3878 if ((index < numArgs) &&
3879 (args[index] == String16("--dispsync"))) {
3880 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003881 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003882 dumpAll = false;
3883 }
Dan Stozab90cf072015-03-05 11:05:59 -08003884
3885 if ((index < numArgs) &&
3886 (args[index] == String16("--static-screen"))) {
3887 index++;
3888 dumpStaticScreenStats(result);
3889 dumpAll = false;
3890 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003891
3892 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003893 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003894 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003895 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003896 dumpAll = false;
3897 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003898
3899 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3900 index++;
3901 dumpWideColorInfo(result);
3902 dumpAll = false;
3903 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003904
3905 if ((index < numArgs) &&
3906 (args[index] == String16("--enable-layer-stats"))) {
3907 index++;
3908 mLayerStats.enable();
3909 dumpAll = false;
3910 }
3911
3912 if ((index < numArgs) &&
3913 (args[index] == String16("--disable-layer-stats"))) {
3914 index++;
3915 mLayerStats.disable();
3916 dumpAll = false;
3917 }
3918
3919 if ((index < numArgs) &&
3920 (args[index] == String16("--clear-layer-stats"))) {
3921 index++;
3922 mLayerStats.clear();
3923 dumpAll = false;
3924 }
3925
3926 if ((index < numArgs) &&
3927 (args[index] == String16("--dump-layer-stats"))) {
3928 index++;
3929 mLayerStats.dump(result);
3930 dumpAll = false;
3931 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003932
3933 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08003934 (args[index] == String16("--frame-composition"))) {
3935 index++;
3936 dumpFrameCompositionInfo(result);
3937 dumpAll = false;
3938 }
3939
3940 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003941 (args[index] == String16("--display-identification"))) {
3942 index++;
3943 dumpDisplayIdentificationData(result);
3944 dumpAll = false;
3945 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003946
3947 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3948 index++;
3949 mTimeStats.parseArgs(asProto, args, index, result);
3950 dumpAll = false;
3951 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003952 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003953
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003954 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003955 if (asProto) {
3956 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3957 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3958 } else {
3959 dumpAllLocked(args, index, result);
3960 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003961 }
3962
Mathias Agopian9795c422009-08-26 16:36:26 -07003963 if (locked) {
3964 mStateLock.unlock();
3965 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003966 }
3967 write(fd, result.string(), result.size());
3968 return NO_ERROR;
3969}
3970
Dan Stozac7014012014-02-14 15:03:43 -08003971void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3972 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003973{
Robert Carr2047fae2016-11-28 14:09:09 -08003974 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003975 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003976 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003977}
3978
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003979void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003980 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003981{
3982 String8 name;
3983 if (index < args.size()) {
3984 name = String8(args[index]);
3985 index++;
3986 }
3987
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003988 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3989 getHwComposer().isConnected(displayId)) {
3990 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3991 const nsecs_t period = activeConfig->getVsyncPeriod();
3992 result.appendFormat("%" PRId64 "\n", period);
3993 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003994
3995 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003996 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003997 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003998 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003999 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004000 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004001 }
Robert Carr2047fae2016-11-28 14:09:09 -08004002 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004003 }
4004}
4005
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004006void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004007 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004008{
4009 String8 name;
4010 if (index < args.size()) {
4011 name = String8(args[index]);
4012 index++;
4013 }
4014
Robert Carr2047fae2016-11-28 14:09:09 -08004015 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004016 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004017 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004018 }
Robert Carr2047fae2016-11-28 14:09:09 -08004019 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004020
Svetoslavd85084b2014-03-20 10:28:31 -07004021 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004022}
4023
Jamie Gennis6547ff42013-07-16 20:12:42 -07004024// This should only be called from the main thread. Otherwise it would need
4025// the lock and should use mCurrentState rather than mDrawingState.
4026void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004027 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004028 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004029 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004030
4031 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4032}
4033
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004034void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004035{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004036 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004037
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004038 if (isLayerTripleBufferingDisabled())
4039 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004040
4041 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004042 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004043 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004044 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004045 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4046 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004047 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004048}
4049
Dan Stozab90cf072015-03-05 11:05:59 -08004050void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4051{
4052 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004053 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4054 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004055 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004056 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004057 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4058 b + 1, bucketTimeSec, percent);
4059 }
David Sodman4a36e932017-11-07 14:29:47 -08004060 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004061 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004062 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004063 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004064 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004065}
4066
Dan Stozae77c7662016-05-13 11:37:28 -07004067void SurfaceFlinger::recordBufferingStats(const char* layerName,
4068 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004069 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4070 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004071 for (const auto& segment : history) {
4072 if (!segment.usedThirdBuffer) {
4073 stats.twoBufferTime += segment.totalTime;
4074 }
4075 if (segment.occupancyAverage < 1.0f) {
4076 stats.doubleBufferedTime += segment.totalTime;
4077 } else if (segment.occupancyAverage < 2.0f) {
4078 stats.tripleBufferedTime += segment.totalTime;
4079 }
4080 ++stats.numSegments;
4081 stats.totalTime += segment.totalTime;
4082 }
4083}
4084
Brian Andersond6927fb2016-07-23 23:37:30 -07004085void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4086 result.appendFormat("Layer frame timestamps:\n");
4087
4088 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4089 const size_t count = currentLayers.size();
4090 for (size_t i=0 ; i<count ; i++) {
4091 currentLayers[i]->dumpFrameEvents(result);
4092 }
4093}
4094
Dan Stozae77c7662016-05-13 11:37:28 -07004095void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4096 result.append("Buffering stats:\n");
4097 result.append(" [Layer name] <Active time> <Two buffer> "
4098 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004099 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004100 typedef std::tuple<std::string, float, float, float> BufferTuple;
4101 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004102 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004103 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004104 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004105 if (stats.numSegments == 0) {
4106 continue;
4107 }
4108 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4109 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4110 stats.totalTime;
4111 float doubleBufferRatio = static_cast<float>(
4112 stats.doubleBufferedTime) / stats.totalTime;
4113 float tripleBufferRatio = static_cast<float>(
4114 stats.tripleBufferedTime) / stats.totalTime;
4115 sorted.insert({activeTime, {name, twoBufferRatio,
4116 doubleBufferRatio, tripleBufferRatio}});
4117 }
4118 for (const auto& sortedPair : sorted) {
4119 float activeTime = sortedPair.first;
4120 const BufferTuple& values = sortedPair.second;
4121 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4122 std::get<0>(values).c_str(), activeTime,
4123 std::get<1>(values), std::get<2>(values),
4124 std::get<3>(values));
4125 }
4126 result.append("\n");
4127}
4128
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004129void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004130 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004131 const int32_t displayId = display->getId();
4132 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4133 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004134 continue;
4135 }
4136
Dominik Laskowski7e045462018-05-30 13:02:02 -07004137 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004138 uint8_t port;
4139 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004140 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004141 result.append("no identification data\n");
4142 continue;
4143 }
4144
4145 if (!isEdid(data)) {
4146 result.append("unknown identification data: ");
4147 for (uint8_t byte : data) {
4148 result.appendFormat("%x ", byte);
4149 }
4150 result.append("\n");
4151 continue;
4152 }
4153
4154 const auto edid = parseEdid(data);
4155 if (!edid) {
4156 result.append("invalid EDID: ");
4157 for (uint8_t byte : data) {
4158 result.appendFormat("%x ", byte);
4159 }
4160 result.append("\n");
4161 continue;
4162 }
4163
4164 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4165 result.append(edid->displayName.data(), edid->displayName.length());
4166 result.append("\"\n");
4167 }
4168 result.append("\n");
4169}
4170
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004171void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004172 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4173 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004174 result.appendFormat("DisplayColorSetting: %s\n",
4175 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004176
4177 // TODO: print out if wide-color mode is active or not
4178
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004179 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004180 const int32_t displayId = display->getId();
4181 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004182 continue;
4183 }
4184
Dominik Laskowski7e045462018-05-30 13:02:02 -07004185 result.appendFormat("Display %d color modes:\n", displayId);
4186 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004187 for (auto&& mode : modes) {
4188 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4189 }
4190
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004191 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004192 result.appendFormat(" Current color mode: %s (%d)\n",
4193 decodeColorMode(currentMode).c_str(), currentMode);
4194 }
4195 result.append("\n");
4196}
4197
David Sodman7e4ae112018-02-09 15:02:28 -08004198void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4199 std::string stringResult;
4200
4201 for (const auto& [token, display] : mDisplays) {
4202 const auto displayId = display->getId();
4203 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4204 continue;
4205 }
4206
4207 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4208 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4209 break;
4210 }
4211 const auto& compositionInfoList = compositionInfoIt->second;
4212 stringResult += base::StringPrintf("Display: %d\n", displayId);
4213 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4214 for (const auto& compositionInfo : compositionInfoList) {
4215 compositionInfo.dump(stringResult, nullptr);
4216 stringResult += base::StringPrintf("\n");
4217 }
4218 }
4219
4220 result.append(stringResult.c_str());
4221}
4222
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004223LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004224 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004225 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4226 const State& state = useDrawing ? mDrawingState : mCurrentState;
4227 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004228 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004229 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004230 });
4231
4232 return layersProto;
4233}
4234
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004235LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004236 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004237
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004238 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004239 resolution->set_w(display.getWidth());
4240 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004241
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004242 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4243 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4244 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004245
Dominik Laskowski7e045462018-05-30 13:02:02 -07004246 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004247 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004248 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004249 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004250 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004251 }
4252 });
4253
4254 return layersProto;
4255}
4256
Mathias Agopian74d211a2013-04-22 16:55:35 +02004257void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4258 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004259{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004260 bool colorize = false;
4261 if (index < args.size()
4262 && (args[index] == String16("--color"))) {
4263 colorize = true;
4264 index++;
4265 }
4266
4267 Colorizer colorizer(colorize);
4268
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004269 // figure out if we're stuck somewhere
4270 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004271 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004272 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4273
4274 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004275 * Dump library configuration.
4276 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004277
4278 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004279 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004280 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004281 appendSfConfigString(result);
4282 appendUiConfigString(result);
4283 appendGuiConfigString(result);
4284 result.append("\n");
4285
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004286 result.append("\nDisplay identification data:\n");
4287 dumpDisplayIdentificationData(result);
4288
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004289 result.append("\nWide-Color information:\n");
4290 dumpWideColorInfo(result);
4291
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004292 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004293 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004294 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004295 result.append(SyncFeatures::getInstance().toString());
4296 result.append("\n");
4297
Andy McFadden41d67d72014-04-25 16:58:34 -07004298 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004299 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004300 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004301
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004302 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4303 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004304 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4305 getHwComposer().isConnected(displayId)) {
4306 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004307 result.appendFormat("Display %d: "
4308 "app phase %" PRId64 " ns, "
4309 "sf phase %" PRId64 " ns, "
4310 "early app phase %" PRId64 " ns, "
4311 "early sf phase %" PRId64 " ns, "
4312 "early app gl phase %" PRId64 " ns, "
4313 "early sf gl phase %" PRId64 " ns, "
4314 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4315 displayId,
4316 vsyncPhaseOffsetNs,
4317 sfVsyncPhaseOffsetNs,
4318 appEarlyOffset,
4319 sfEarlyOffset,
4320 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004321 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004322 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004323 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004324 result.append("\n");
4325
Dan Stozab90cf072015-03-05 11:05:59 -08004326 // Dump static screen stats
4327 result.append("\n");
4328 dumpStaticScreenStats(result);
4329 result.append("\n");
4330
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004331 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4332
Dan Stozae77c7662016-05-13 11:37:28 -07004333 dumpBufferingStats(result);
4334
Andy McFadden4803b742012-09-24 19:07:20 -07004335 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004336 * Dump the visible layer list
4337 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004338 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004339 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004340 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4341 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004342 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004343
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004344 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004345 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004346 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004347 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004348
David Sodman7e4ae112018-02-09 15:02:28 -08004349 result.append("\nFrame-Composition information:\n");
4350 dumpFrameCompositionInfo(result);
4351 result.append("\n");
4352
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004353 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004354 * Dump Display state
4355 */
4356
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004357 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004358 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004359 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004360 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004361 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004362 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004363 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004364
4365 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004366 * Dump SurfaceFlinger global state
4367 */
4368
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004369 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004370 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004371 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004372
Mathias Agopian888c8222012-08-04 21:10:38 -07004373 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004374 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004375
David Sodmanbc815282017-11-05 18:57:52 -08004376 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004377
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004378 if (display) {
4379 display->undefinedRegion.dump(result, "undefinedRegion");
4380 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4381 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004382 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004383 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004384 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004385 mTransactionFlags, !mGpuToCpuSupported);
4386
4387 if (display) {
4388 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4389 result.appendFormat(" refresh-rate : %f fps\n"
4390 " x-dpi : %f\n"
4391 " y-dpi : %f\n",
4392 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4393 activeConfig->getDpiY());
4394 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004395
Mathias Agopian74d211a2013-04-22 16:55:35 +02004396 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004397 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004398
4399 /*
4400 * VSYNC state
4401 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004402 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004403 result.append("\n");
4404
4405 /*
4406 * HWC layer minidump
4407 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004408 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004409 const int32_t displayId = display->getId();
4410 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004411 continue;
4412 }
4413
Dominik Laskowski7e045462018-05-30 13:02:02 -07004414 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004415 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004416 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004417 result.append("\n");
4418 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004419
4420 /*
4421 * Dump HWComposer state
4422 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004423 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004424 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004425 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004426 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004427 result.appendFormat(" h/w composer %s\n",
4428 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004429 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004430
4431 /*
4432 * Dump gralloc state
4433 */
4434 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4435 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004436
4437 /*
4438 * Dump VrFlinger state if in use.
4439 */
4440 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4441 result.append("VrFlinger state:\n");
4442 result.append(mVrFlinger->Dump().c_str());
4443 result.append("\n");
4444 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004445}
4446
Dominik Laskowski7e045462018-05-30 13:02:02 -07004447const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004448 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004449 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004450 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004451 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004452 }
4453 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004454
4455 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4456 static const Vector<sp<Layer>> empty;
4457 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004458}
4459
Keun young Park63f165f2012-08-31 10:53:36 -07004460bool SurfaceFlinger::startDdmConnection()
4461{
4462 void* libddmconnection_dso =
4463 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4464 if (!libddmconnection_dso) {
4465 return false;
4466 }
4467 void (*DdmConnection_start)(const char* name);
4468 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004469 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004470 if (!DdmConnection_start) {
4471 dlclose(libddmconnection_dso);
4472 return false;
4473 }
4474 (*DdmConnection_start)(getServiceName());
4475 return true;
4476}
4477
Chia-I Wu28f320b2018-05-03 11:02:56 -07004478void SurfaceFlinger::updateColorMatrixLocked() {
4479 mat4 colorMatrix;
4480 if (mGlobalSaturationFactor != 1.0f) {
4481 // Rec.709 luma coefficients
4482 float3 luminance{0.213f, 0.715f, 0.072f};
4483 luminance *= 1.0f - mGlobalSaturationFactor;
4484 mat4 saturationMatrix = mat4(
4485 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4486 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4487 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4488 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4489 );
4490 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4491 } else {
4492 colorMatrix = mClientColorMatrix * mDaltonizer();
4493 }
4494
4495 if (mCurrentState.colorMatrix != colorMatrix) {
4496 mCurrentState.colorMatrix = colorMatrix;
4497 mCurrentState.colorMatrixChanged = true;
4498 setTransactionFlags(eTransactionNeeded);
4499 }
4500}
4501
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004502status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004503#pragma clang diagnostic push
4504#pragma clang diagnostic error "-Wswitch-enum"
4505 switch (static_cast<ISurfaceComposerTag>(code)) {
4506 // These methods should at minimum make sure that the client requested
4507 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004508 case BOOT_FINISHED:
4509 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004510 case CREATE_CONNECTION:
4511 case CREATE_DISPLAY:
4512 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004513 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004514 case GET_ACTIVE_COLOR_MODE:
4515 case GET_ANIMATION_FRAME_STATS:
4516 case GET_HDR_CAPABILITIES:
4517 case SET_ACTIVE_CONFIG:
4518 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004519 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004520 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004521 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4522 IPCThreadState* ipc = IPCThreadState::self();
4523 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4524 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004525 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004526 }
Robert Carr1db73f62016-12-21 12:58:51 -08004527 return OK;
4528 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004529 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004530 IPCThreadState* ipc = IPCThreadState::self();
4531 const int pid = ipc->getCallingPid();
4532 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004533 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4534 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004535 return PERMISSION_DENIED;
4536 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004537 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004538 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004539 // Used by apps to hook Choreographer to SurfaceFlinger.
4540 case CREATE_DISPLAY_EVENT_CONNECTION:
4541 // The following calls are currently used by clients that do not
4542 // request necessary permissions. However, they do not expose any secret
4543 // information, so it is OK to pass them.
4544 case AUTHENTICATE_SURFACE:
4545 case GET_ACTIVE_CONFIG:
4546 case GET_BUILT_IN_DISPLAY:
4547 case GET_DISPLAY_COLOR_MODES:
4548 case GET_DISPLAY_CONFIGS:
4549 case GET_DISPLAY_STATS:
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -07004550 case GET_DISPLAY_VIEWPORT:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004551 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4552 // Calling setTransactionState is safe, because you need to have been
4553 // granted a reference to Client* and Handle* to do anything with it.
4554 case SET_TRANSACTION_STATE:
4555 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4556 case CREATE_SCOPED_CONNECTION: {
4557 return OK;
4558 }
4559 case CAPTURE_LAYERS:
4560 case CAPTURE_SCREEN: {
4561 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004562 IPCThreadState* ipc = IPCThreadState::self();
4563 const int pid = ipc->getCallingPid();
4564 const int uid = ipc->getCallingUid();
4565 if ((uid != AID_GRAPHICS) &&
4566 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4567 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4568 return PERMISSION_DENIED;
4569 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004570 return OK;
4571 }
4572 // The following codes are deprecated and should never be allowed to access SF.
4573 case CONNECT_DISPLAY_UNUSED:
4574 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4575 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4576 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004577 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004578 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004579
4580 // These codes are used for the IBinder protocol to either interrogate the recipient
4581 // side of the transaction for its canonical interface descriptor or to dump its state.
4582 // We let them pass by default.
4583 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4584 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4585 code == IBinder::SYSPROPS_TRANSACTION) {
4586 return OK;
4587 }
4588 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4589 // in onTransact verifies that the user is root, and has access to use SF.
4590 if (code >= 1000 && code <= 1029) {
4591 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4592 return OK;
4593 }
4594 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4595 return PERMISSION_DENIED;
4596#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004597}
4598
Ana Krulec13be8ad2018-08-21 02:43:56 +00004599status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4600 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004601 status_t credentialCheck = CheckTransactCodeCredentials(code);
4602 if (credentialCheck != OK) {
4603 return credentialCheck;
4604 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004605
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004606 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4607 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004608 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004609 IPCThreadState* ipc = IPCThreadState::self();
4610 const int uid = ipc->getCallingUid();
4611 if (CC_UNLIKELY(uid != AID_SYSTEM
4612 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004613 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004614 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004615 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004616 return PERMISSION_DENIED;
4617 }
4618 int n;
4619 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004620 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004621 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004622 return NO_ERROR;
4623 case 1002: // SHOW_UPDATES
4624 n = data.readInt32();
4625 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004626 invalidateHwcGeometry();
4627 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004628 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004629 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004630 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004631 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004632 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004633 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004634 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004635 setTransactionFlags(
4636 eTransactionNeeded|
4637 eDisplayTransactionNeeded|
4638 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004639 return NO_ERROR;
4640 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004641 case 1006:{ // send empty update
4642 signalRefresh();
4643 return NO_ERROR;
4644 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004645 case 1008: // toggle use of hw composer
4646 n = data.readInt32();
4647 mDebugDisableHWC = n ? 1 : 0;
4648 invalidateHwcGeometry();
4649 repaintEverything();
4650 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004651 case 1009: // toggle use of transform hint
4652 n = data.readInt32();
4653 mDebugDisableTransformHint = n ? 1 : 0;
4654 invalidateHwcGeometry();
4655 repaintEverything();
4656 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004657 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004658 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004659 reply->writeInt32(0);
4660 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004661 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004662 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004663 return NO_ERROR;
4664 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004665 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004666 if (!display) {
4667 return NAME_NOT_FOUND;
4668 }
4669
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004670 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004671 return NO_ERROR;
4672 }
4673 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004674 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004675 // daltonize
4676 n = data.readInt32();
4677 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004678 case 1:
4679 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4680 break;
4681 case 2:
4682 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4683 break;
4684 case 3:
4685 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4686 break;
4687 default:
4688 mDaltonizer.setType(ColorBlindnessType::None);
4689 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004690 }
4691 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004692 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004693 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004694 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004695 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004696
4697 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004698 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004699 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004700 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004701 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004702 // apply a color matrix
4703 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004704 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004705 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004706 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004707 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004708 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004709 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004710 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004711 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004712 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004713 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004714
4715 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4716 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004717 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004718 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4719 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4720 }
4721
Chia-I Wu28f320b2018-05-03 11:02:56 -07004722 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004723 return NO_ERROR;
4724 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004725 // This is an experimental interface
4726 // Needs to be shifted to proper binder interface when we productize
4727 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004728 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004729 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004730 return NO_ERROR;
4731 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004732 case 1017: {
4733 n = data.readInt32();
4734 mForceFullDamage = static_cast<bool>(n);
4735 return NO_ERROR;
4736 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004737 case 1018: { // Modify Choreographer's phase offset
4738 n = data.readInt32();
4739 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4740 return NO_ERROR;
4741 }
4742 case 1019: { // Modify SurfaceFlinger's phase offset
4743 n = data.readInt32();
4744 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4745 return NO_ERROR;
4746 }
Irvel468051e2016-06-13 16:44:44 -07004747 case 1020: { // Layer updates interceptor
4748 n = data.readInt32();
4749 if (n) {
4750 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004751 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004752 }
4753 else{
4754 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004755 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004756 }
4757 return NO_ERROR;
4758 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004759 case 1021: { // Disable HWC virtual displays
4760 n = data.readInt32();
4761 mUseHwcVirtualDisplays = !n;
4762 return NO_ERROR;
4763 }
Romain Guy0147a172017-06-01 13:53:56 -07004764 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004765 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004766 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004767
Chia-I Wu28f320b2018-05-03 11:02:56 -07004768 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004769 return NO_ERROR;
4770 }
Romain Guy54f154a2017-10-24 21:40:32 +01004771 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004772 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004773 invalidateHwcGeometry();
4774 repaintEverything();
4775 return NO_ERROR;
4776 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004777 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
4778 // deprecate 1024 if they can.
4779 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01004780 reply->writeBool(hasWideColorDisplay);
4781 return NO_ERROR;
4782 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004783 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004784 n = data.readInt32();
4785 if (n) {
4786 ALOGV("LayerTracing enabled");
4787 mTracing.enable();
4788 doTracing("tracing.enable");
4789 reply->writeInt32(NO_ERROR);
4790 } else {
4791 ALOGV("LayerTracing disabled");
4792 status_t err = mTracing.disable();
4793 reply->writeInt32(err);
4794 }
4795 return NO_ERROR;
4796 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004797 case 1026: { // Get layer tracing status
4798 reply->writeBool(mTracing.isEnabled());
4799 return NO_ERROR;
4800 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004801 // Is a DisplayColorSetting supported?
4802 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004803 const auto display = getDefaultDisplayDevice();
4804 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004805 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004806 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004807
4808 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4809 switch (setting) {
4810 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004811 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004812 break;
4813 case DisplayColorSetting::UNMANAGED:
4814 reply->writeBool(true);
4815 break;
4816 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004817 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004818 break;
4819 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004820 reply->writeBool(
4821 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004822 break;
4823 }
4824 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004825 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004826 // Is VrFlinger active?
4827 case 1028: {
4828 Mutex::Autolock _l(mStateLock);
4829 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4830 return NO_ERROR;
4831 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004832 case 1029: {
4833 // Code 1029 is an experimental feature that allows applications to
4834 // simulate a high frequency panel by setting a multiplier and divisor
4835 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07004836 // 0, then the code simply return the current multiplier and divisor.
4837 HWC2::Device::FrequencyScaler frequencyScaler;
4838 frequencyScaler.multiplier = data.readInt32();
4839 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07004840
David Sodman44b5de02018-08-21 16:28:53 -07004841 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
4842 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
4843 reply->writeInt32(frequencyScaler.multiplier);
4844 reply->writeInt32(frequencyScaler.divisor);
4845 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07004846 }
4847
David Sodman44b5de02018-08-21 16:28:53 -07004848 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07004849 enableHardwareVsync();
4850 } else {
4851 disableHardwareVsync(true);
4852 }
David Sodman44b5de02018-08-21 16:28:53 -07004853 mPrimaryDispSync->scalePeriod(frequencyScaler);
4854 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07004855
David Sodman44b5de02018-08-21 16:28:53 -07004856 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
4857 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
4858
4859 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
4860 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
4861
4862 onHotplugReceived(getBE().mComposerSequenceId,
4863 hwcDisplayId, HWC2::Connection::Disconnected);
4864 onHotplugReceived(getBE().mComposerSequenceId,
4865 hwcDisplayId, HWC2::Connection::Connected);
4866 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
4867 reply->writeInt32(frequencyScaler.multiplier);
4868 reply->writeInt32(frequencyScaler.divisor);
4869
David Sodman6d46c1e2018-07-13 12:59:48 -07004870 return NO_ERROR;
4871 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004872 // Is device color managed?
4873 case 1030: {
4874 reply->writeBool(useColorManagement);
4875 return NO_ERROR;
4876 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004877 }
4878 }
4879 return err;
4880}
4881
Steven Thomas6d8110b2017-08-31 18:24:21 -07004882void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004883 android_atomic_or(1, &mRepaintEverything);
4884 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004885}
4886
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004887// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4888class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004889public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004890 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4891 ~WindowDisconnector() {
4892 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004893 }
4894
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004895private:
4896 ANativeWindow* mWindow;
4897 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004898};
4899
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004900status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4901 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4902 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4903 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004904 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004905 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004906
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004907 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004908
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004909 const auto display = getDisplayDeviceLocked(displayToken);
4910 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004911
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004912 const Rect& dispScissor = display->getScissor();
4913 if (!dispScissor.isEmpty()) {
4914 sourceCrop.set(dispScissor);
4915 // adb shell screencap will default reqWidth and reqHeight to zeros.
4916 if (reqWidth == 0 || reqHeight == 0) {
Yiwei Zhangec90e582018-08-21 22:11:37 -07004917 reqWidth = uint32_t(display->getViewport().width());
4918 reqHeight = uint32_t(display->getViewport().height());
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004919 }
4920 }
4921
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004922 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004923
4924 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004925 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004926 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004927}
4928
4929status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004930 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004931 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004932 ATRACE_CALL();
4933
4934 class LayerRenderArea : public RenderArea {
4935 public:
Robert Carr578038f2018-03-09 12:25:24 -08004936 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4937 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004938 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004939 mLayer(layer),
4940 mCrop(crop),
4941 mFlinger(flinger),
4942 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004943 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004944 Rect getBounds() const override {
4945 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004946 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004947 }
Marissa Wall61c58622018-07-18 10:12:20 -07004948 int getHeight() const override {
4949 return mLayer->getActiveHeight(mLayer->getDrawingState());
4950 }
4951 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004952 bool isSecure() const override { return false; }
4953 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004954 Rect getSourceCrop() const override {
4955 if (mCrop.isEmpty()) {
4956 return getBounds();
4957 } else {
4958 return mCrop;
4959 }
4960 }
Robert Carr578038f2018-03-09 12:25:24 -08004961 class ReparentForDrawing {
4962 public:
4963 const sp<Layer>& oldParent;
4964 const sp<Layer>& newParent;
4965
4966 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4967 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004968 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004969 }
Robert Carr15eae092018-03-23 13:43:53 -07004970 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004971 };
4972
4973 void render(std::function<void()> drawLayers) override {
4974 if (!mChildrenOnly) {
4975 mTransform = mLayer->getTransform().inverse();
4976 drawLayers();
4977 } else {
4978 Rect bounds = getBounds();
4979 screenshotParentLayer =
4980 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4981 bounds.getWidth(), bounds.getHeight(), 0);
4982
4983 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4984 drawLayers();
4985 }
4986 }
chaviwa76b2712017-09-20 12:02:26 -07004987
chaviwa76b2712017-09-20 12:02:26 -07004988 private:
chaviw7206d492017-11-10 16:16:12 -08004989 const sp<Layer> mLayer;
4990 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004991
4992 // In the "childrenOnly" case we reparent the children to a screenshot
4993 // layer which has no properties set and which does not draw.
4994 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07004995 ui::Transform mTransform;
Robert Carr578038f2018-03-09 12:25:24 -08004996
4997 SurfaceFlinger* mFlinger;
4998 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004999 };
5000
5001 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5002 auto parent = layerHandle->owner.promote();
5003
chaviw7206d492017-11-10 16:16:12 -08005004 if (parent == nullptr || parent->isPendingRemoval()) {
5005 ALOGE("captureLayers called with a removed parent");
5006 return NAME_NOT_FOUND;
5007 }
5008
Robert Carr578038f2018-03-09 12:25:24 -08005009 const int uid = IPCThreadState::self()->getCallingUid();
5010 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5011 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5012 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5013 return PERMISSION_DENIED;
5014 }
5015
chaviw7206d492017-11-10 16:16:12 -08005016 Rect crop(sourceCrop);
5017 if (sourceCrop.width() <= 0) {
5018 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005019 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005020 }
5021
5022 if (sourceCrop.height() <= 0) {
5023 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005024 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005025 }
5026
5027 int32_t reqWidth = crop.width() * frameScale;
5028 int32_t reqHeight = crop.height() * frameScale;
5029
Robert Carr578038f2018-03-09 12:25:24 -08005030 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005031
Robert Carr578038f2018-03-09 12:25:24 -08005032 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005033 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5034 if (!layer->isVisible()) {
5035 return;
Robert Carr578038f2018-03-09 12:25:24 -08005036 } else if (childrenOnly && layer == parent.get()) {
5037 return;
chaviwa76b2712017-09-20 12:02:26 -07005038 }
5039 visitor(layer);
5040 });
5041 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005042 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005043}
5044
5045status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5046 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005047 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005048 bool useIdentityTransform) {
5049 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005050
Iris Chang7501ed62018-04-30 14:45:42 +08005051 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005052
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005053 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5054 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5055 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5056 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005057
5058 // This mutex protects syncFd and captureResult for communication of the return values from the
5059 // main thread back to this Binder thread
5060 std::mutex captureMutex;
5061 std::condition_variable captureCondition;
5062 std::unique_lock<std::mutex> captureLock(captureMutex);
5063 int syncFd = -1;
5064 std::optional<status_t> captureResult;
5065
Robert Carr03480e22018-01-04 16:02:06 -08005066 const int uid = IPCThreadState::self()->getCallingUid();
5067 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5068
Dominik Laskowski8c001672018-05-30 16:52:06 -07005069 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005070 // If there is a refresh pending, bug out early and tell the binder thread to try again
5071 // after the refresh.
5072 if (mRefreshPending) {
5073 ATRACE_NAME("Skipping screenshot for now");
5074 std::unique_lock<std::mutex> captureLock(captureMutex);
5075 captureResult = std::make_optional<status_t>(EAGAIN);
5076 captureCondition.notify_one();
5077 return;
5078 }
5079
5080 status_t result = NO_ERROR;
5081 int fd = -1;
5082 {
5083 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005084 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005085 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5086 useIdentityTransform, forSystem, &fd);
5087 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005088 }
5089
5090 {
5091 std::unique_lock<std::mutex> captureLock(captureMutex);
5092 syncFd = fd;
5093 captureResult = std::make_optional<status_t>(result);
5094 captureCondition.notify_one();
5095 }
5096 });
5097
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005098 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005099 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005100 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005101 while (*captureResult == EAGAIN) {
5102 captureResult.reset();
5103 result = postMessageAsync(message);
5104 if (result != NO_ERROR) {
5105 return result;
5106 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005107 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005108 }
5109 result = *captureResult;
5110 }
5111
5112 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005113 sync_wait(syncFd, -1);
5114 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005115 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005116
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005117 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005118}
5119
chaviwa76b2712017-09-20 12:02:26 -07005120void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5121 TraverseLayersFunction traverseLayers, bool yswap,
5122 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005123 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005124
Lloyd Pique144e1162017-12-20 16:44:52 -08005125 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005126
5127 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005128 const auto raWidth = renderArea.getWidth();
5129 const auto raHeight = renderArea.getHeight();
5130
5131 const auto reqWidth = renderArea.getReqWidth();
5132 const auto reqHeight = renderArea.getReqHeight();
5133 Rect sourceCrop = renderArea.getSourceCrop();
5134
Iris Chang7501ed62018-04-30 14:45:42 +08005135 bool filtering = false;
5136 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5137 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5138 static_cast<int32_t>(reqHeight) != raWidth;
5139 } else {
5140 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5141 static_cast<int32_t>(reqHeight) != raHeight;
5142 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005143
Dan Stozac1879002014-05-22 15:59:05 -07005144 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005145 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005146 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005147 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005148 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005149 ui::Transform tr;
Iris Chang7501ed62018-04-30 14:45:42 +08005150 uint32_t flags = 0x00;
5151 switch (mPrimaryDisplayOrientation) {
5152 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005153 flags = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005154 break;
5155 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005156 flags = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005157 break;
5158 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005159 flags = ui::Transform::ROT_270;
Iris Chang7501ed62018-04-30 14:45:42 +08005160 break;
5161 }
5162 tr.set(flags, raWidth, raHeight);
5163 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005164 }
5165
5166 // ensure that sourceCrop is inside screen
5167 if (sourceCrop.left < 0) {
5168 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5169 }
chaviwa76b2712017-09-20 12:02:26 -07005170 if (sourceCrop.right > raWidth) {
5171 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005172 }
5173 if (sourceCrop.top < 0) {
5174 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5175 }
chaviwa76b2712017-09-20 12:02:26 -07005176 if (sourceCrop.bottom > raHeight) {
5177 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005178 }
5179
Chia-I Wu36574d92018-05-16 10:54:36 -07005180 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5181 engine.setOutputDataSpace(Dataspace::SRGB);
5182 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005183
Mathias Agopian180f10d2013-04-10 22:55:41 -07005184 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005185 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005186
Peiyong Linefefaac2018-08-17 12:27:51 -07005187 ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
Iris Chang7501ed62018-04-30 14:45:42 +08005188 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5189 // convert hw orientation into flag presentation
5190 // here inverse transform needed
5191 uint8_t hw_rot_90 = 0x00;
5192 uint8_t hw_flip_hv = 0x00;
5193 switch (mPrimaryDisplayOrientation) {
5194 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005195 hw_rot_90 = ui::Transform::ROT_90;
5196 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005197 break;
5198 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005199 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005200 break;
5201 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005202 hw_rot_90 = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005203 break;
5204 }
5205
5206 // transform flags operation
5207 // 1) flip H V if both have ROT_90 flag
5208 // 2) XOR these flags
Peiyong Linefefaac2018-08-17 12:27:51 -07005209 uint8_t rotation_rot_90 = rotation & ui::Transform::ROT_90;
5210 uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005211 if (rotation_rot_90 & hw_rot_90) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005212 rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005213 }
Peiyong Linefefaac2018-08-17 12:27:51 -07005214 rotation = static_cast<ui::Transform::orientation_flags>
Iris Chang7501ed62018-04-30 14:45:42 +08005215 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5216 }
5217
Mathias Agopian180f10d2013-04-10 22:55:41 -07005218 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005219 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005220 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005221 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005222
chaviw50da5042018-04-09 13:49:37 -07005223 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005224 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005225 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005226
chaviwa76b2712017-09-20 12:02:26 -07005227 traverseLayers([&](Layer* layer) {
5228 if (filtering) layer->setFiltering(true);
David Sodmanfb95bcc2017-12-22 15:45:30 -08005229 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005230 if (filtering) layer->setFiltering(false);
5231 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005232}
5233
chaviwa76b2712017-09-20 12:02:26 -07005234status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5235 TraverseLayersFunction traverseLayers,
5236 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005237 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005238 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005239 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005240 ATRACE_CALL();
5241
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005242 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005243
5244 traverseLayers([&](Layer* layer) {
5245 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5246 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005247
Robert Carr03480e22018-01-04 16:02:06 -08005248 // We allow the system server to take screenshots of secure layers for
5249 // use in situations like the Screen-rotation animation and place
5250 // the impetus on WindowManager to not persist them.
5251 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005252 ALOGW("FB is protected: PERMISSION_DENIED");
5253 return PERMISSION_DENIED;
5254 }
5255
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005256 // this binds the given EGLImage as a framebuffer for the
5257 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005258 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005259 if (bufferBond.getStatus() != NO_ERROR) {
5260 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005261 return INVALID_OPERATION;
5262 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005263
Dan Stozaabcda352017-06-01 14:37:39 -07005264 // this will in fact render into our dequeued buffer
5265 // via an FBO, which means we didn't have to create
5266 // an EGLSurface and therefore we're not
5267 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005268 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005269
Dan Stozaabcda352017-06-01 14:37:39 -07005270 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005271 getRenderEngine().finish();
5272 *outSyncFd = -1;
5273
chaviwa76b2712017-09-20 12:02:26 -07005274 const auto reqWidth = renderArea.getReqWidth();
5275 const auto reqHeight = renderArea.getReqHeight();
5276
Dan Stozaabcda352017-06-01 14:37:39 -07005277 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5278 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005279 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005280 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005281 } else {
5282 base::unique_fd syncFd = getRenderEngine().flush();
5283 if (syncFd < 0) {
5284 getRenderEngine().finish();
5285 }
5286 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005287 }
5288
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005289 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005290}
5291
Mathias Agopiand5556842013-09-19 17:08:37 -07005292void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005293 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005294 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005295 for (size_t y = 0; y < h; y++) {
5296 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5297 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005298 if (p[x] != 0xFF000000) return;
5299 }
5300 }
chaviwa76b2712017-09-20 12:02:26 -07005301 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005302
Robert Carr2047fae2016-11-28 14:09:09 -08005303 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005304 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005305 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005306 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5307 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5308 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5309 static_cast<float>(state.color.a));
5310 i++;
5311 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005312 }
5313}
5314
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005315// ---------------------------------------------------------------------------
5316
Dan Stoza412903f2017-04-27 13:42:17 -07005317void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5318 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005319}
5320
Dan Stoza412903f2017-04-27 13:42:17 -07005321void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5322 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005323}
5324
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005325void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5326 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005327 const LayerVector::Visitor& visitor) {
5328 // We loop through the first level of layers without traversing,
5329 // as we need to interpret min/max layer Z in the top level Z space.
5330 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005331 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005332 continue;
5333 }
5334 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005335 // relative layers are traversed in Layer::traverseInZOrder
5336 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005337 continue;
5338 }
5339 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005340 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005341 return;
5342 }
chaviwa76b2712017-09-20 12:02:26 -07005343 if (!layer->isVisible()) {
5344 return;
5345 }
5346 visitor(layer);
5347 });
5348 }
5349}
5350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005351}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005352
Lloyd Pique074e8122018-07-26 12:57:23 -07005353
Mathias Agopian3f844832013-08-07 21:24:32 -07005354#if defined(__gl_h_)
5355#error "don't include gl/gl.h in this file"
5356#endif
5357
5358#if defined(__gl2_h_)
5359#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005360#endif