blob: 7680f2a3aaf82b1f3d03e68d295bd350bb346092 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080067#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080070#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070071#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080072#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070073#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080074#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070076#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Steven Thomasb02664d2017-07-26 18:48:28 -070081#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070082#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070083#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070084#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070085#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include "Effects/Daltonizer.h"
88
Mathias Agopian875d8e12013-06-07 15:35:48 -070089#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070090#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070091
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080093#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
94#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090095#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090096
chaviw1d044282017-09-27 12:19:28 -070097#include <layerproto/LayerProtoParser.h>
98
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099#define DISPLAY_COUNT 1
100
Mathias Agopianfee2b462013-07-03 12:34:01 -0700101/*
102 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
103 * black pixels.
104 */
105#define DEBUG_SCREENSHOTS false
106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108
Jaesoo Lee43518572017-01-23 19:03:16 +0900109using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700111using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700112using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700113using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700114using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
Steven Thomasb02664d2017-07-26 18:48:28 -0700116namespace {
117class ConditionalLock {
118public:
119 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
120 if (lock) {
121 mMutex.lock();
122 }
123 }
124 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
125private:
126 Mutex& mMutex;
127 bool mLocked;
128};
129} // namespace anonymous
130
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131// ---------------------------------------------------------------------------
132
Mathias Agopian99b49842011-06-27 16:05:52 -0700133const String16 sHardwareTest("android.permission.HARDWARE_TEST");
134const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
135const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
136const String16 sDump("android.permission.DUMP");
137
138// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800139int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
140int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700141int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700142bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800143uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800144bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800145bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800146int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800147// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600148bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700149
Kalle Raitaa099a242017-01-11 11:17:29 -0800150
151std::string getHwcServiceName() {
152 char value[PROPERTY_VALUE_MAX] = {};
153 property_get("debug.sf.hwc_service_name", value, "default");
154 ALOGI("Using HWComposer service: '%s'", value);
155 return std::string(value);
156}
157
158bool useTrebleTestingOverride() {
159 char value[PROPERTY_VALUE_MAX] = {};
160 property_get("debug.sf.treble_testing_override", value, "false");
161 ALOGI("Treble testing override: '%s'", value);
162 return std::string(value) == "true";
163}
164
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800165std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
166 switch(displayColorSetting) {
167 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700168 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800169 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700170 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800171 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700172 return std::string("Enhanced");
173 default:
174 return std::string("Unknown ") +
175 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800176 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800177}
178
Lloyd Pique99d3da52018-01-22 17:48:03 -0800179NativeWindowSurface::~NativeWindowSurface() = default;
180
181namespace impl {
182
183class NativeWindowSurface final : public android::NativeWindowSurface {
184public:
185 static std::unique_ptr<android::NativeWindowSurface> create(
186 const sp<IGraphicBufferProducer>& producer) {
187 return std::make_unique<NativeWindowSurface>(producer);
188 }
189
190 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
191 : surface(new Surface(producer, false)) {}
192
193 ~NativeWindowSurface() override = default;
194
195private:
196 sp<ANativeWindow> getNativeWindow() const override { return surface; }
197
198 void preallocateBuffers() override { surface->allocateBuffers(); }
199
200 sp<Surface> surface;
201};
202
203} // namespace impl
204
David Sodmanbc815282017-11-05 18:57:52 -0800205SurfaceFlingerBE::SurfaceFlingerBE()
206 : mHwcServiceName(getHwcServiceName()),
207 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800208 mFrameBuckets(),
209 mTotalTime(0),
210 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800211 mComposerSequenceId(0) {
212}
213
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800214SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800215 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800216 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700217 mTransactionPending(false),
218 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700219 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700220 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700221 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700223 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800225 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800226 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800227 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700229 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700230 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700231 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700232 mDebugInSwapBuffers(0),
233 mLastSwapBufferTime(0),
234 mDebugInTransaction(0),
235 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700236 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000237 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700238 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700239 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800240 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800241 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700242 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800243 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800244 mCreateBufferQueue(&BufferQueue::createBufferQueue),
245 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800246
247SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800248 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800249
250 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
251 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
252
253 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
254 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
255
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800256 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
257 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700259 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
260 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
261
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700262 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
263 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
264
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800265 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
266 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
267
Steven Thomas050b2c82017-03-06 11:45:16 -0800268 // Vr flinger is only enabled on Daydream ready devices.
269 useVrFlinger = getBool< ISurfaceFlingerConfigs,
270 &ISurfaceFlingerConfigs::useVrFlinger>(false);
271
Fabien Sanglard1971b632017-03-10 14:50:03 -0800272 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
273 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
274
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600275 hasWideColorDisplay =
276 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
277
Iris Chang7501ed62018-04-30 14:45:42 +0800278 V1_1::DisplayOrientation primaryDisplayOrientation =
279 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
280 V1_1::DisplayOrientation::ORIENTATION_0);
281
282 switch (primaryDisplayOrientation) {
283 case V1_1::DisplayOrientation::ORIENTATION_90:
284 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
285 break;
286 case V1_1::DisplayOrientation::ORIENTATION_180:
287 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
288 break;
289 case V1_1::DisplayOrientation::ORIENTATION_270:
290 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
291 break;
292 default:
293 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
294 break;
295 }
296 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
297
David Sodman99974d22017-11-28 12:04:33 -0800298 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700299
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800300 // debugging stuff...
301 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700302
Mathias Agopianb4b17302013-03-20 18:36:41 -0700303 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700304 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700305
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800306 property_get("debug.sf.showupdates", value, "0");
307 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700308
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700309 property_get("debug.sf.ddms", value, "0");
310 mDebugDDMS = atoi(value);
311 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700312 if (!startDdmConnection()) {
313 // start failed, and DDMS debugging not enabled
314 mDebugDDMS = 0;
315 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700316 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700317 ALOGI_IF(mDebugRegion, "showupdates enabled");
318 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700319
320 property_get("debug.sf.disable_backpressure", value, "0");
321 mPropagateBackpressure = !atoi(value);
322 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700323
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800324 property_get("debug.sf.enable_hwc_vds", value, "0");
325 mUseHwcVirtualDisplays = atoi(value);
326 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800327
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800328 property_get("ro.sf.disable_triple_buffer", value, "1");
329 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800330 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700331
Yiwei Zhang243b3782018-05-15 17:40:04 -0700332 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700333 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
334 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
335
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200336 property_get("debug.sf.early_phase_offset_ns", value, "-1");
337 const int earlySfOffsetNs = atoi(value);
338
339 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
340 const int earlyGlSfOffsetNs = atoi(value);
341
342 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
343 const int earlyAppOffsetNs = atoi(value);
344
345 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
346 const int earlyGlAppOffsetNs = atoi(value);
347
348 const VSyncModulator::Offsets earlyOffsets =
349 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
350 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
351 const VSyncModulator::Offsets earlyGlOffsets =
352 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
353 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
354 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
355 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700356
Romain Guy11d63f42017-07-20 12:47:14 -0700357 // We should be reading 'persist.sys.sf.color_saturation' here
358 // but since /data may be encrypted, we need to wait until after vold
359 // comes online to attempt to read the property. The property is
360 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800361
362 if (useTrebleTestingOverride()) {
363 // Without the override SurfaceFlinger cannot connect to HIDL
364 // services that are not listed in the manifests. Considered
365 // deriving the setting from the set service name, but it
366 // would be brittle if the name that's not 'default' is used
367 // for production purposes later on.
368 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
369 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370}
371
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800372void SurfaceFlinger::onFirstRef()
373{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800374 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800375}
376
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800377SurfaceFlinger::~SurfaceFlinger()
378{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800379}
380
Dan Stozac7014012014-02-14 15:03:43 -0800381void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800382{
383 // the window manager died on us. prepare its eulogy.
384
Andy McFadden13a082e2012-08-24 10:16:42 -0700385 // restore initial conditions (default device unblank, etc)
386 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800387
388 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700389 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800390}
391
Robert Carr1db73f62016-12-21 12:58:51 -0800392static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700393 status_t err = client->initCheck();
394 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800395 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800396 }
Robert Carr1db73f62016-12-21 12:58:51 -0800397 return nullptr;
398}
399
400sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
401 return initClient(new Client(this));
402}
403
404sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
405 const sp<IGraphicBufferProducer>& gbp) {
406 if (authenticateSurfaceTexture(gbp) == false) {
407 return nullptr;
408 }
409 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
410 if (layer == nullptr) {
411 return nullptr;
412 }
413
414 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415}
416
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700417sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
418 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700419{
420 class DisplayToken : public BBinder {
421 sp<SurfaceFlinger> flinger;
422 virtual ~DisplayToken() {
423 // no more references, this display must be terminated
424 Mutex::Autolock _l(flinger->mStateLock);
425 flinger->mCurrentState.displays.removeItem(this);
426 flinger->setTransactionFlags(eDisplayTransactionNeeded);
427 }
428 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700429 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700430 : flinger(flinger) {
431 }
432 };
433
434 sp<BBinder> token = new DisplayToken(this);
435
436 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700437 DisplayDeviceState info;
438 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700439 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700440 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700441 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800442 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700443 return token;
444}
445
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700446void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700447 Mutex::Autolock _l(mStateLock);
448
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700449 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700450 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700451 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700452 return;
453 }
454
455 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700456 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700457 ALOGE("destroyDisplay called for non-virtual display");
458 return;
459 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700460 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700461 mCurrentState.displays.removeItemsAt(idx);
462 setTransactionFlags(eDisplayTransactionNeeded);
463}
464
Mathias Agopiane57f2922012-08-09 16:29:12 -0700465sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700466 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700467 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800468 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700469 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700470 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700471}
472
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800473void SurfaceFlinger::bootFinished()
474{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700475 if (mStartPropertySetThread->join() != NO_ERROR) {
476 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800477 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800478 const nsecs_t now = systemTime();
479 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000480 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700481
482 // wait patiently for the window manager death
483 const String16 name("window");
484 sp<IBinder> window(defaultServiceManager()->getService(name));
485 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700486 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700487 }
488
Steven Thomas050b2c82017-03-06 11:45:16 -0800489 if (mVrFlinger) {
490 mVrFlinger->OnBootFinished();
491 }
492
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700493 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700494 // formerly we would just kill the process, but we now ask it to exit so it
495 // can choose where to stop the animation.
496 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700497
498 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
499 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
500 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700501
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800502 postMessageAsync(new LambdaMessage([this] {
503 readPersistentProperties();
504 mBootStage = BootStage::FINISHED;
505 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800506}
507
Dan Stoza436ccf32018-06-21 12:10:12 -0700508uint32_t SurfaceFlinger::getNewTexture() {
509 {
510 std::lock_guard lock(mTexturePoolMutex);
511 if (!mTexturePool.empty()) {
512 uint32_t name = mTexturePool.back();
513 mTexturePool.pop_back();
514 ATRACE_INT("TexturePoolSize", mTexturePool.size());
515 return name;
516 }
517
518 // The pool was too small, so increase it for the future
519 ++mTexturePoolSize;
520 }
521
522 // The pool was empty, so we need to get a new texture name directly using a
523 // blocking call to the main thread
524 uint32_t name = 0;
525 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
526 return name;
527}
528
Mathias Agopian3f844832013-08-07 21:24:32 -0700529void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700530 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700531}
532
Lloyd Piquee83f9312018-02-01 12:53:17 -0800533class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700535 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000536 const char* name) :
537 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700538 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700539 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000540 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
541 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700542 mDispSync(dispSync),
543 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700544 mVsyncMutex(),
545 mPhaseOffset(phaseOffset),
546 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700547
Lloyd Piquee83f9312018-02-01 12:53:17 -0800548 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700549
Lloyd Piquee83f9312018-02-01 12:53:17 -0800550 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700551 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700552 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000553 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700554 static_cast<DispSync::Callback*>(this));
555 if (err != NO_ERROR) {
556 ALOGE("error registering vsync callback: %s (%d)",
557 strerror(-err), err);
558 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700559 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700560 } else {
561 status_t err = mDispSync->removeEventListener(
562 static_cast<DispSync::Callback*>(this));
563 if (err != NO_ERROR) {
564 ALOGE("error unregistering vsync callback: %s (%d)",
565 strerror(-err), err);
566 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700567 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700569 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700570 }
571
Lloyd Piquee83f9312018-02-01 12:53:17 -0800572 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700573 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574 mCallback = callback;
575 }
576
Lloyd Piquee83f9312018-02-01 12:53:17 -0800577 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700578 Mutex::Autolock lock(mVsyncMutex);
579
580 // Normalize phaseOffset to [0, period)
581 auto period = mDispSync->getPeriod();
582 phaseOffset %= period;
583 if (phaseOffset < 0) {
584 // If we're here, then phaseOffset is in (-period, 0). After this
585 // operation, it will be in (0, period)
586 phaseOffset += period;
587 }
588 mPhaseOffset = phaseOffset;
589
590 // If we're not enabled, we don't need to mess with the listeners
591 if (!mEnabled) {
592 return;
593 }
594
Dan Stoza84d619e2018-03-28 17:07:36 -0700595 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
596 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700597 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700598 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700599 strerror(-err), err);
600 }
601 }
602
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700603private:
604 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800605 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700606 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700607 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700608 callback = mCallback;
609
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700610 if (mTraceVsync) {
611 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700612 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700613 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700614 }
615
Peiyong Lin566a3b42018-01-09 18:22:43 -0800616 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700617 callback->onVSyncEvent(when);
618 }
619 }
620
Tim Murray4a4e4a22016-04-19 16:29:23 +0000621 const char* const mName;
622
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700623 int mValue;
624
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700625 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700626 const String8 mVsyncOnLabel;
627 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700628
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700629 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700630
631 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800632 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700633
634 Mutex mVsyncMutex; // Protects the following
635 nsecs_t mPhaseOffset;
636 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700637};
638
Lloyd Piquee83f9312018-02-01 12:53:17 -0800639class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700640public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800641 InjectVSyncSource() = default;
642 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700643
Lloyd Piquee83f9312018-02-01 12:53:17 -0800644 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700645 std::lock_guard<std::mutex> lock(mCallbackMutex);
646 mCallback = callback;
647 }
648
Lloyd Piquee83f9312018-02-01 12:53:17 -0800649 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700650 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700651 if (mCallback) {
652 mCallback->onVSyncEvent(when);
653 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700654 }
655
Lloyd Piquee83f9312018-02-01 12:53:17 -0800656 void setVSyncEnabled(bool) override {}
657 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700658
659private:
660 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800661 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700662};
663
Wei Wangf9b05ee2017-07-19 20:59:39 -0700664// Do not call property_set on main thread which will be blocked by init
665// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700666void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700667 ALOGI( "SurfaceFlinger's main thread ready to run. "
668 "Initializing graphics H/W...");
669
Thierry Strudel2924d012017-08-14 15:19:37 -0700670 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900671
Steven Thomasb02664d2017-07-26 18:48:28 -0700672 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800673
Steven Thomasb02664d2017-07-26 18:48:28 -0700674 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800675 mEventThreadSource =
676 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
677 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800678 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700679 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800680 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800681 "appEventThread");
682 mSfEventThreadSource =
683 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
684 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800685
Lloyd Pique24b0a482018-03-09 18:52:26 -0800686 mSFEventThread =
687 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700688 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800689 [this](nsecs_t timestamp) {
690 mInterceptor->saveVSyncEvent(timestamp);
691 },
692 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800693 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200694 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800695
Steven Thomasb02664d2017-07-26 18:48:28 -0700696 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800697 getBE().mRenderEngine =
698 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
699 hasWideColorDisplay
700 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
701 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800702 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700703
704 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
705 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800706 getBE().mHwc.reset(
707 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700708 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800709 // Process any initial hotplug and resulting display changes.
710 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700711 const auto display = getDefaultDisplayDeviceLocked();
712 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
713 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
714 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800715
Lloyd Piquefcd86612017-12-14 17:15:36 -0800716 // make the default display GLContext current so that we can create textures
717 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700718 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800719
Steven Thomas050b2c82017-03-06 11:45:16 -0800720 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700721 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700722 // This callback is called from the vr flinger dispatch thread. We
723 // need to call signalTransaction(), which requires holding
724 // mStateLock when we're not on the main thread. Acquiring
725 // mStateLock from the vr flinger dispatch thread might trigger a
726 // deadlock in surface flinger (see b/66916578), so post a message
727 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700728 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700729 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
730 mVrFlingerRequestsDisplay = requestDisplay;
731 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700732 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800733 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700734 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
735 getHwComposer()
736 .getHwcDisplayId(display->getId())
737 .value_or(0),
738 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800739 if (!mVrFlinger) {
740 ALOGE("Failed to start vrflinger");
741 }
742 }
743
Lloyd Pique379adc12018-01-22 17:31:47 -0800744 mEventControlThread = std::make_unique<impl::EventControlThread>(
745 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700746
Mathias Agopian92a979a2012-08-02 18:32:23 -0700747 // initialize our drawing state
748 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700749
Andy McFadden13a082e2012-08-24 10:16:42 -0700750 // set initial conditions (e.g. unblank default device)
751 initializeDisplays();
752
David Sodmanbc815282017-11-05 18:57:52 -0800753 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700754
Wei Wangf9b05ee2017-07-19 20:59:39 -0700755 // Inform native graphics APIs whether the present timestamp is supported:
756 if (getHwComposer().hasCapability(
757 HWC2::Capability::PresentFenceIsNotReliable)) {
758 mStartPropertySetThread = new StartPropertySetThread(false);
759 } else {
760 mStartPropertySetThread = new StartPropertySetThread(true);
761 }
762
763 if (mStartPropertySetThread->Start() != NO_ERROR) {
764 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800765 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800766
Chia-I Wud49d6692018-06-27 07:17:41 +0800767 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
768 // is used to saturate legacy sRGB content. However, to make sure the same color under
769 // Display P3 will be saturated to the same color, we intentionally break the API spec
770 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
771 // such saturation matrix on Display P3 is understood fully, the API should always return
772 // identify matrix.
773 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
774 Dataspace::SRGB_LINEAR);
775
776 // we will apply this on Display P3.
777 if (mEnhancedSaturationMatrix != mat4()) {
778 ColorSpace srgb(ColorSpace::sRGB());
779 ColorSpace displayP3(ColorSpace::DisplayP3());
780 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
781 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
782 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
783 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800784
Dan Stoza9e56aa02015-11-02 13:00:03 -0800785 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700786}
787
Romain Guy11d63f42017-07-20 12:47:14 -0700788void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700789 Mutex::Autolock _l(mStateLock);
790
Romain Guy11d63f42017-07-20 12:47:14 -0700791 char value[PROPERTY_VALUE_MAX];
792
793 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800794 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700795 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800796 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100797
798 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700799 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700800}
801
Mathias Agopiana67e4182012-06-19 17:26:12 -0700802void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800803 // Start boot animation service by setting a property mailbox
804 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700805 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800806 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700807 if (mStartPropertySetThread->join() != NO_ERROR) {
808 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800809 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700810}
811
Mathias Agopian875d8e12013-06-07 15:35:48 -0700812size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800813 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700814}
815
Mathias Agopian875d8e12013-06-07 15:35:48 -0700816size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800817 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700818}
819
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800820// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800821
Jamie Gennis582270d2011-08-17 18:19:00 -0700822bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800823 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800824 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800825 return authenticateSurfaceTextureLocked(bufferProducer);
826}
827
828bool SurfaceFlinger::authenticateSurfaceTextureLocked(
829 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800830 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800831 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800832}
833
Brian Anderson6b376712017-04-04 10:51:39 -0700834status_t SurfaceFlinger::getSupportedFrameTimestamps(
835 std::vector<FrameEvent>* outSupported) const {
836 *outSupported = {
837 FrameEvent::REQUESTED_PRESENT,
838 FrameEvent::ACQUIRE,
839 FrameEvent::LATCH,
840 FrameEvent::FIRST_REFRESH_START,
841 FrameEvent::LAST_REFRESH_START,
842 FrameEvent::GPU_COMPOSITION_DONE,
843 FrameEvent::DEQUEUE_READY,
844 FrameEvent::RELEASE,
845 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700846 ConditionalLock _l(mStateLock,
847 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700848 if (!getHwComposer().hasCapability(
849 HWC2::Capability::PresentFenceIsNotReliable)) {
850 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
851 }
852 return NO_ERROR;
853}
854
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700855status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
856 Vector<DisplayInfo>* configs) {
857 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 return BAD_VALUE;
859 }
860
Jesse Hall692c7232012-11-08 15:41:56 -0800861 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700862 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
863 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700864 type = i;
865 break;
866 }
867 }
868
869 if (type < 0) {
870 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700871 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700872
Mathias Agopian8b736f12012-08-13 17:54:26 -0700873 // TODO: Not sure if display density should handled by SF any longer
874 class Density {
875 static int getDensityFromProperty(char const* propName) {
876 char property[PROPERTY_VALUE_MAX];
877 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800878 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700879 density = atoi(property);
880 }
881 return density;
882 }
883 public:
884 static int getEmuDensity() {
885 return getDensityFromProperty("qemu.sf.lcd_density"); }
886 static int getBuildDensity() {
887 return getDensityFromProperty("ro.sf.lcd_density"); }
888 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700889
Dan Stoza7f7da322014-05-02 15:26:25 -0700890 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700891
Steven Thomas6d8110b2017-08-31 18:24:21 -0700892 ConditionalLock _l(mStateLock,
893 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700895 DisplayInfo info = DisplayInfo();
896
Dan Stoza9e56aa02015-11-02 13:00:03 -0800897 float xdpi = hwConfig->getDpiX();
898 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700899
900 if (type == DisplayDevice::DISPLAY_PRIMARY) {
901 // The density of the device is provided by a build property
902 float density = Density::getBuildDensity() / 160.0f;
903 if (density == 0) {
904 // the build doesn't provide a density -- this is wrong!
905 // use xdpi instead
906 ALOGE("ro.sf.lcd_density must be defined as a build property");
907 density = xdpi / 160.0f;
908 }
909 if (Density::getEmuDensity()) {
910 // if "qemu.sf.lcd_density" is specified, it overrides everything
911 xdpi = ydpi = density = Density::getEmuDensity();
912 density /= 160.0f;
913 }
914 info.density = density;
915
916 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700917 const auto display = getDefaultDisplayDeviceLocked();
918 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700919 } else {
920 // TODO: where should this value come from?
921 static const int TV_DENSITY = 213;
922 info.density = TV_DENSITY / 160.0f;
923 info.orientation = 0;
924 }
925
Dan Stoza9e56aa02015-11-02 13:00:03 -0800926 info.w = hwConfig->getWidth();
927 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700928 info.xdpi = xdpi;
929 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800930 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900931 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800932
Andy McFadden91b2ca82014-06-13 14:04:23 -0700933 // This is how far in advance a buffer must be queued for
934 // presentation at a given time. If you want a buffer to appear
935 // on the screen at time N, you must submit the buffer before
936 // (N - presentationDeadline).
937 //
938 // Normally it's one full refresh period (to give SF a chance to
939 // latch the buffer), but this can be reduced by configuring a
940 // DispSync offset. Any additional delays introduced by the hardware
941 // composer or panel must be accounted for here.
942 //
943 // We add an additional 1ms to allow for processing time and
944 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800945 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800946 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700947
948 // All non-virtual displays are currently considered secure.
949 info.secure = true;
950
Iris Chang7501ed62018-04-30 14:45:42 +0800951 if (type == DisplayDevice::DISPLAY_PRIMARY &&
952 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
953 std::swap(info.w, info.h);
954 }
955
Michael Wright28f24d02016-07-12 13:30:53 -0700956 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700957 }
958
Dan Stoza7f7da322014-05-02 15:26:25 -0700959 return NO_ERROR;
960}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700961
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
963 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700964 return BAD_VALUE;
965 }
966
967 // FIXME for now we always return stats for the primary display
968 memset(stats, 0, sizeof(*stats));
969 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
970 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
971 return NO_ERROR;
972}
973
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700974int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
975 const auto display = getDisplayDevice(displayToken);
976 if (!display) {
977 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800978 return BAD_VALUE;
979 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700980
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700981 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700982}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700983
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700984void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
985 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700986 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700987 return;
988 }
989
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700990 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700991 ALOGW("Trying to set config for virtual display");
992 return;
993 }
994
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700995 display->setActiveConfig(mode);
996 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700997}
998
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700999status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001000 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001001 Vector<DisplayInfo> configs;
1002 getDisplayConfigs(displayToken, &configs);
1003 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
1004 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
1005 configs.size());
1006 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001007 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001008 const auto display = getDisplayDevice(displayToken);
1009 if (!display) {
1010 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
1011 displayToken.get());
1012 } else if (display->isVirtual()) {
1013 ALOGW("Attempt to set active config %d for virtual display", mode);
1014 } else {
1015 setActiveConfigInternal(display, mode);
1016 }
1017 }));
1018
Mathias Agopian888c8222012-08-04 21:10:38 -07001019 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001020}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001021status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1022 Vector<ColorMode>* outColorModes) {
1023 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001024 return BAD_VALUE;
1025 }
1026
Michael Wright28f24d02016-07-12 13:30:53 -07001027 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001028 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1029 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001030 type = i;
1031 break;
1032 }
1033 }
1034
1035 if (type < 0) {
1036 return type;
1037 }
1038
Peiyong Lina52f0292018-03-14 17:26:31 -07001039 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001040 {
1041 ConditionalLock _l(mStateLock,
1042 std::this_thread::get_id() != mMainThreadId);
1043 modes = getHwComposer().getColorModes(type);
1044 }
Michael Wright28f24d02016-07-12 13:30:53 -07001045 outColorModes->clear();
1046 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1047
1048 return NO_ERROR;
1049}
1050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1052 if (const auto display = getDisplayDevice(displayToken)) {
1053 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001054 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001055 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001056}
1057
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1059 Dataspace dataSpace, RenderIntent renderIntent) {
1060 ColorMode currentMode = display->getActiveColorMode();
1061 Dataspace currentDataSpace = display->getCompositionDataSpace();
1062 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001063
Peiyong Lin38e9a562018-04-10 16:24:20 -07001064 if (mode == currentMode && dataSpace == currentDataSpace &&
1065 renderIntent == currentRenderIntent) {
1066 return;
1067 }
1068
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001069 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001070 ALOGW("Trying to set config for virtual display");
1071 return;
1072 }
1073
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001074 display->setActiveColorMode(mode);
1075 display->setCompositionDataSpace(dataSpace);
1076 display->setActiveRenderIntent(renderIntent);
1077 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001078
1079 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1081 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001082}
1083
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001084status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001085 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086 Vector<ColorMode> modes;
1087 getDisplayColorModes(displayToken, &modes);
1088 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1089 if (mode < ColorMode::NATIVE || !exists) {
1090 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1091 decodeColorMode(mode).c_str(), mode, displayToken.get());
1092 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001093 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001094 const auto display = getDisplayDevice(displayToken);
1095 if (!display) {
1096 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1097 decodeColorMode(mode).c_str(), mode, displayToken.get());
1098 } else if (display->isVirtual()) {
1099 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1100 decodeColorMode(mode).c_str(), mode);
1101 } else {
1102 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1103 RenderIntent::COLORIMETRIC);
1104 }
1105 }));
1106
Michael Wright28f24d02016-07-12 13:30:53 -07001107 return NO_ERROR;
1108}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001109
Svetoslavd85084b2014-03-20 10:28:31 -07001110status_t SurfaceFlinger::clearAnimationFrameStats() {
1111 Mutex::Autolock _l(mStateLock);
1112 mAnimFrameTracker.clearStats();
1113 return NO_ERROR;
1114}
1115
1116status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1117 Mutex::Autolock _l(mStateLock);
1118 mAnimFrameTracker.getStats(outStats);
1119 return NO_ERROR;
1120}
1121
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1123 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001124 Mutex::Autolock _l(mStateLock);
1125
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126 const auto display = getDisplayDeviceLocked(displayToken);
1127 if (!display) {
1128 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001129 return BAD_VALUE;
1130 }
1131
Peiyong Linfb069302018-04-25 14:34:31 -07001132 // At this point the DisplayDeivce should already be set up,
1133 // meaning the luminance information is already queried from
1134 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001135 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001136 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1137 capabilities.getDesiredMaxLuminance(),
1138 capabilities.getDesiredMaxAverageLuminance(),
1139 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001140
1141 return NO_ERROR;
1142}
1143
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001144status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001145 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001146 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001147
Chia-I Wu90f669f2017-10-05 14:24:41 -07001148 if (mInjectVSyncs == enable) {
1149 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001150 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151
1152 if (enable) {
1153 ALOGV("VSync Injections enabled");
1154 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001155 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001156 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001157 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001158 impl::EventThread::InterceptVSyncsCallback(),
1159 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001160 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001161 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001162 } else {
1163 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001164 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001165 }
1166
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001167 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001168 }));
1169
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001170 return NO_ERROR;
1171}
1172
1173status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001174 Mutex::Autolock _l(mStateLock);
1175
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001176 if (!mInjectVSyncs) {
1177 ALOGE("VSync Injections not enabled");
1178 return BAD_VALUE;
1179 }
1180 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1181 ALOGV("Injecting VSync inside SurfaceFlinger");
1182 mVSyncInjector->onInjectSyncEvent(when);
1183 }
1184 return NO_ERROR;
1185}
1186
Lloyd Pique755e3192018-01-31 16:46:15 -08001187status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1188 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001189 IPCThreadState* ipc = IPCThreadState::self();
1190 const int pid = ipc->getCallingPid();
1191 const int uid = ipc->getCallingUid();
1192 if ((uid != AID_SHELL) &&
1193 !PermissionCache::checkPermission(sDump, pid, uid)) {
1194 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1195 return PERMISSION_DENIED;
1196 }
1197
1198 // Try to acquire a lock for 1s, fail gracefully
1199 const status_t err = mStateLock.timedLock(s2ns(1));
1200 const bool locked = (err == NO_ERROR);
1201 if (!locked) {
1202 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1203 return TIMED_OUT;
1204 }
1205
1206 outLayers->clear();
1207 mCurrentState.traverseInZOrder([&](Layer* layer) {
1208 outLayers->push_back(layer->getLayerDebugInfo());
1209 });
1210
1211 mStateLock.unlock();
1212 return NO_ERROR;
1213}
1214
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001215// ----------------------------------------------------------------------------
1216
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001217sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1218 ISurfaceComposer::VsyncSource vsyncSource) {
1219 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1220 return mSFEventThread->createEventConnection();
1221 } else {
1222 return mEventThread->createEventConnection();
1223 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001224}
1225
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001226// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001227
1228void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001229 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001230}
1231
1232void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001233 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234}
1235
1236void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001237 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001238}
1239
1240void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001241 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001242 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001243}
1244
1245status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001246 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001247 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001248}
1249
1250status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001251 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001252 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001253 if (res == NO_ERROR) {
1254 msg->wait();
1255 }
1256 return res;
1257}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001258
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001259void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001260 do {
1261 waitForEvent();
1262 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001263}
1264
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001265void SurfaceFlinger::enableHardwareVsync() {
1266 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001267 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001268 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001269 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001270 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001271 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001272}
1273
Jesse Hall948fe0c2013-10-14 12:56:09 -07001274void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275 Mutex::Autolock _l(mHWVsyncLock);
1276
Jesse Hall948fe0c2013-10-14 12:56:09 -07001277 if (makeAvailable) {
1278 mHWVsyncAvailable = true;
1279 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001280 // Hardware vsync is not currently available, so abort the resync
1281 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001282 return;
1283 }
1284
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001285 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1286 if (!getHwComposer().isConnected(displayId)) {
1287 return;
1288 }
1289
1290 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001291 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001292
1293 mPrimaryDispSync.reset();
1294 mPrimaryDispSync.setPeriod(period);
1295
1296 if (!mPrimaryHWVsyncEnabled) {
1297 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001298 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001299 mPrimaryHWVsyncEnabled = true;
1300 }
1301}
1302
Jesse Hall948fe0c2013-10-14 12:56:09 -07001303void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001304 Mutex::Autolock _l(mHWVsyncLock);
1305 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001306 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001307 mPrimaryDispSync.endResync();
1308 mPrimaryHWVsyncEnabled = false;
1309 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001310 if (makeUnavailable) {
1311 mHWVsyncAvailable = false;
1312 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001313}
1314
Tim Murray4a4e4a22016-04-19 16:29:23 +00001315void SurfaceFlinger::resyncWithRateLimit() {
1316 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001317
1318 // No explicit locking is needed here since EventThread holds a lock while calling this method
1319 static nsecs_t sLastResyncAttempted = 0;
1320 const nsecs_t now = systemTime();
1321 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001322 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001323 }
Dan Stoza57164302017-05-08 14:03:54 -07001324 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001325}
1326
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001327void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1328 int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001329 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001330 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001331 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001332 return;
1333 }
1334
1335 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001336 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001337 return;
1338 }
1339
Jamie Gennisd1700752013-10-14 12:22:52 -07001340 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001341
Jamie Gennisd1700752013-10-14 12:22:52 -07001342 { // Scope for the lock
1343 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001345 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001346 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001347 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001348
1349 if (needsHwVsync) {
1350 enableHardwareVsync();
1351 } else {
1352 disableHardwareVsync(false);
1353 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001354}
1355
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001356void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001357 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1358 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001359}
1360
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001361void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001362 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001363 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001364 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001365
Lloyd Piqueba04e622017-12-14 17:11:26 -08001366 // Ignore events that do not have the right sequenceId.
1367 if (sequenceId != getBE().mComposerSequenceId) {
1368 return;
1369 }
1370
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 // Only lock if we're not on the main thread. This function is normally
1372 // called on a hwbinder thread, but for the primary display it's called on
1373 // the main thread with the state lock already held, so don't attempt to
1374 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001375 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001376
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001377 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001378
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001379 if (std::this_thread::get_id() == mMainThreadId) {
1380 // Process all pending hot plug events immediately if we are on the main thread.
1381 processDisplayHotplugEventsLocked();
1382 }
1383
Lloyd Piqueba04e622017-12-14 17:11:26 -08001384 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001385}
1386
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001387void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001388 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001389 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001391 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001392 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001393}
1394
Dan Stoza9e56aa02015-11-02 13:00:03 -08001395void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001396 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001397 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001398 getHwComposer().setVsyncEnabled(disp,
1399 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001400}
1401
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001403void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001404 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001405 // Clear the drawing state so that the logic inside of
1406 // handleTransactionLocked will fire. It will determine the delta between
1407 // mCurrentState and mDrawingState and re-apply all changes when we make the
1408 // transition.
1409 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001410 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001411 mDisplays.clear();
1412}
1413
Steven Thomas050b2c82017-03-06 11:45:16 -08001414void SurfaceFlinger::updateVrFlinger() {
1415 if (!mVrFlinger)
1416 return;
1417 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001418 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001419 return;
1420 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001421
David Sodman105b7dc2017-11-04 20:28:14 -07001422 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001423 ALOGE("Vr flinger is only supported for remote hardware composer"
1424 " service connections. Ignoring request to transition to vr"
1425 " flinger.");
1426 mVrFlingerRequestsDisplay = false;
1427 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001428 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001429
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001431
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001432 const auto display = getDefaultDisplayDeviceLocked();
1433 LOG_ALWAYS_FATAL_IF(!display);
1434 const int currentDisplayPowerMode = display->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001435
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001437 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001439
Steven Thomasb02664d2017-07-26 18:48:28 -07001440 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001441 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001442 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1443 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001444 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001445
David Sodman105b7dc2017-11-04 20:28:14 -07001446 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1447 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001448
1449 if (vrFlingerRequestsDisplay) {
1450 mVrFlinger->GrantDisplayOwnership();
1451 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001452 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001453 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001454
1455 mVisibleRegionsDirty = true;
1456 invalidateHwcGeometry();
1457
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001458 // Re-enable default display.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001459 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001460
Steven Thomasb02664d2017-07-26 18:48:28 -07001461 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001462 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001463 const nsecs_t period = activeConfig->getVsyncPeriod();
1464 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001465
Steven Thomasb02664d2017-07-26 18:48:28 -07001466 // Use phase of 0 since phase is not known.
1467 // Use latency of 0, which will snap to the ideal latency.
1468 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001469
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001470 android_atomic_or(1, &mRepaintEverything);
1471 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001472}
1473
Mathias Agopian4fec8732012-06-29 14:12:52 -07001474void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001475 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001476 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001477 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001478 bool frameMissed = !mHadClientComposition &&
1479 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001480 (mPreviousPresentFence->getSignalTime() ==
1481 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001482 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001483 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001484 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001485 mTimeStats.incrementMissedFrames();
1486 if (mPropagateBackpressure) {
1487 signalLayerUpdate();
1488 break;
1489 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001490 }
Dan Stoza50182882016-07-08 12:02:20 -07001491
Steven Thomas050b2c82017-03-06 11:45:16 -08001492 // Now that we're going to make it to the handleMessageTransaction()
1493 // call below it's safe to call updateVrFlinger(), which will
1494 // potentially trigger a display handoff.
1495 updateVrFlinger();
1496
Dan Stoza6b9454d2014-11-07 16:00:59 -08001497 bool refreshNeeded = handleMessageTransaction();
1498 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001499 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001500 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001501 // Signal a refresh if a transaction modified the window state,
1502 // a new buffer was latched, or if HWC has requested a full
1503 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504 signalRefresh();
1505 }
1506 break;
1507 }
1508 case MessageQueue::REFRESH: {
1509 handleMessageRefresh();
1510 break;
1511 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001512 }
1513}
1514
Dan Stoza6b9454d2014-11-07 16:00:59 -08001515bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001516 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001517 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001518 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001519 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001520 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001521 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001522}
1523
Dan Stoza6b9454d2014-11-07 16:00:59 -08001524bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001525 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001526 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001527}
1528
1529void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001530 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001531
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001532 mRefreshPending = false;
1533
Chia-I Wu30505fb2018-03-26 16:20:31 -07001534 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001535
Chia-I Wu30505fb2018-03-26 16:20:31 -07001536 preComposition(refreshStartTime);
1537 rebuildLayerStacks();
1538 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001539 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001540 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001541 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001542 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001543 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001544
Dan Stozabfbffeb2016-07-21 14:49:33 -07001545 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001546 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001547 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001548 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001549 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001550 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001551
Dan Stoza9e56aa02015-11-02 13:00:03 -08001552 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001553}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001554
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555void SurfaceFlinger::doDebugFlashRegions()
1556{
1557 // is debugging enabled
1558 if (CC_LIKELY(!mDebugRegion))
1559 return;
1560
1561 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001562 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001563 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001564 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001565 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001566 if (!dirtyRegion.isEmpty()) {
1567 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001568 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001569
1570 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001571 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001572 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001573 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1574
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001575 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001576 }
1577 }
1578 }
1579
1580 postFramebuffer();
1581
1582 if (mDebugRegion > 1) {
1583 usleep(mDebugRegion * 1000);
1584 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001585
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001586 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001587 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001588 continue;
1589 }
1590
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001591 status_t result = display->prepareFrame(*getBE().mHwc);
1592 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001593 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001594 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001595}
1596
Adrian Roos1e1a1282017-11-01 19:05:31 +01001597void SurfaceFlinger::doTracing(const char* where) {
1598 ATRACE_CALL();
1599 ATRACE_NAME(where);
1600 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001601 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001602 }
1603}
1604
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001605void SurfaceFlinger::logLayerStats() {
1606 ATRACE_CALL();
1607 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001608 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001609 if (display->isPrimary()) {
1610 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001611 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001612 }
1613 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001614
1615 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001616 }
1617}
1618
Chia-I Wu30505fb2018-03-26 16:20:31 -07001619void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001620{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001621 ATRACE_CALL();
1622 ALOGV("preComposition");
1623
Mathias Agopiancd60f992012-08-16 16:28:27 -07001624 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001625 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001626 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001627 needExtraInvalidate = true;
1628 }
Robert Carr2047fae2016-11-28 14:09:09 -08001629 });
1630
Mathias Agopiancd60f992012-08-16 16:28:27 -07001631 if (needExtraInvalidate) {
1632 signalLayerUpdate();
1633 }
1634}
1635
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001636void SurfaceFlinger::updateCompositorTiming(
1637 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1638 std::shared_ptr<FenceTime>& presentFenceTime) {
1639 // Update queue of past composite+present times and determine the
1640 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001641 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001642 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001643 while (!getBE().mCompositePresentTimes.empty()) {
1644 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001645 // Cached values should have been updated before calling this method,
1646 // which helps avoid duplicate syscalls.
1647 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1648 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1649 break;
1650 }
1651 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001652 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001653 }
1654
1655 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001656 while (getBE().mCompositePresentTimes.size() > 16) {
1657 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001658 }
1659
Brian Andersond0010582017-03-07 13:20:31 -08001660 setCompositorTimingSnapped(
1661 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1662}
1663
1664void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1665 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001666 // Integer division and modulo round toward 0 not -inf, so we need to
1667 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001668 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001669 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1670 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1671
Brian Andersond0010582017-03-07 13:20:31 -08001672 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1673 if (idealLatency <= 0) {
1674 idealLatency = vsyncInterval;
1675 }
1676
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001677 // Snap the latency to a value that removes scheduling jitter from the
1678 // composition and present times, which often have >1ms of jitter.
1679 // Reducing jitter is important if an app attempts to extrapolate
1680 // something (such as user input) to an accurate diasplay time.
1681 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1682 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001683 nsecs_t bias = vsyncInterval / 2;
1684 int64_t extraVsyncs =
1685 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1686 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1687 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001688
David Sodman99974d22017-11-28 12:04:33 -08001689 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1690 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1691 getBE().mCompositorTiming.interval = vsyncInterval;
1692 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001693}
1694
Chia-I Wu30505fb2018-03-26 16:20:31 -07001695void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001696{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001697 ATRACE_CALL();
1698 ALOGV("postComposition");
1699
Brian Anderson3546a3f2016-07-14 11:51:14 -07001700 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001701 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001702 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001703 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001704 }
1705
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001706 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001707 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001708
David Sodman73beded2017-11-15 11:56:06 -08001709 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001710 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001711 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001712 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001713 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001714 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001715 } else {
1716 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1717 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001718
David Sodman73beded2017-11-15 11:56:06 -08001719 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001720 mPreviousPresentFence =
1721 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1722 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001723 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001724
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001725 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1726 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1727
Chia-I Wu30505fb2018-03-26 16:20:31 -07001728 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001729 // when we started doing work for this frame, but that should be okay
1730 // since updateCompositorTiming has snapping logic.
1731 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001732 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001733 CompositorTiming compositorTiming;
1734 {
David Sodman99974d22017-11-28 12:04:33 -08001735 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1736 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001737 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001738
Robert Carr2047fae2016-11-28 14:09:09 -08001739 mDrawingState.traverseInZOrder([&](Layer* layer) {
1740 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001741 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001742 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001743 recordBufferingStats(layer->getName().string(),
1744 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001745 }
Robert Carr2047fae2016-11-28 14:09:09 -08001746 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001747
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001748 if (presentFenceTime->isValid()) {
1749 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001750 enableHardwareVsync();
1751 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001752 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001753 }
1754 }
1755
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001756 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001757 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001758 enableHardwareVsync();
1759 }
1760 }
1761
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001762 if (mAnimCompositionPending) {
1763 mAnimCompositionPending = false;
1764
Brian Anderson4e606e32017-03-16 15:34:57 -07001765 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001766 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001767 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001768 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001769 // The HWC doesn't support present fences, so use the refresh
1770 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001771 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001772 mAnimFrameTracker.setActualPresentTime(presentTime);
1773 }
1774 mAnimFrameTracker.advanceFrame();
1775 }
Dan Stozab90cf072015-03-05 11:05:59 -08001776
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001777 mTimeStats.incrementTotalFrames();
1778 if (mHadClientComposition) {
1779 mTimeStats.incrementClientCompositionFrames();
1780 }
1781
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001782 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001783 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001784 return;
1785 }
1786
1787 nsecs_t currentTime = systemTime();
1788 if (mHasPoweredOff) {
1789 mHasPoweredOff = false;
1790 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001791 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001792 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001793 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1794 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001795 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001796 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001797 }
David Sodman4a36e932017-11-07 14:29:47 -08001798 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001799 }
David Sodman4a36e932017-11-07 14:29:47 -08001800 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001801
1802 {
1803 std::lock_guard lock(mTexturePoolMutex);
1804 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1805 if (refillCount > 0) {
1806 const size_t offset = mTexturePool.size();
1807 mTexturePool.resize(mTexturePoolSize);
1808 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1809 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1810 }
1811 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001812}
1813
1814void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001815 ATRACE_CALL();
1816 ALOGV("rebuildLayerStacks");
1817
Mathias Agopiancd60f992012-08-16 16:28:27 -07001818 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001819 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001820 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001821 mVisibleRegionsDirty = false;
1822 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001823
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001824 for (const auto& pair : mDisplays) {
1825 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001826 Region opaqueRegion;
1827 Region dirtyRegion;
1828 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001829 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001830 const Transform& tr = display->getTransform();
1831 const Rect bounds = display->getBounds();
1832 if (display->isPoweredOn()) {
1833 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001834
Jeff Sharkey76488112017-02-27 14:15:18 -07001835 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001836 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001837 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001838 Region drawRegion(tr.transform(
1839 layer->visibleNonTransparentRegion));
1840 drawRegion.andSelf(bounds);
1841 if (!drawRegion.isEmpty()) {
1842 layersSortedByZ.add(layer);
1843 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001844 // Clear out the HWC layer if this layer was
1845 // previously visible, but no longer is
Dominik Laskowski7e045462018-05-30 13:02:02 -07001846 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001847 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001848 } else {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001849 // WM changes display->layerStack upon sleep/awake.
Chia-I Wu30505fb2018-03-26 16:20:31 -07001850 // Here we make sure we delete the HWC layers even if
1851 // WM changed their layer stack.
Dominik Laskowski7e045462018-05-30 13:02:02 -07001852 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001853 }
1854
1855 // If a layer is not going to get a release fence because
1856 // it is invisible, but it is also going to release its
1857 // old buffer, add it to the list of layers needing
1858 // fences.
1859 if (hwcLayerDestroyed) {
1860 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1861 mLayersWithQueuedFrames.cend(), layer);
1862 if (found != mLayersWithQueuedFrames.cend()) {
1863 layersNeedingFences.add(layer);
1864 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001865 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001866 });
1867 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001868 display->setVisibleLayersSortedByZ(layersSortedByZ);
1869 display->setLayersNeedingFences(layersNeedingFences);
1870 display->undefinedRegion.set(bounds);
1871 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1872 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001873 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001874 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001875}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001876
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001877// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001878// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001879// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001880// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001881// The returned HDR data space is one of
1882// - Dataspace::UNKNOWN
1883// - Dataspace::BT2020_HLG
1884// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001885Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1886 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001887 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001888 *outHdrDataSpace = Dataspace::UNKNOWN;
1889
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001890 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001891 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001892 case Dataspace::V0_SCRGB:
1893 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001894 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001895 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001896 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001897 case Dataspace::BT2020_PQ:
1898 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001899 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001900 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001901 case Dataspace::BT2020_HLG:
1902 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001903 // When there's mixed PQ content and HLG content, we set the HDR
1904 // data space to be BT2020_PQ and convert HLG to PQ.
1905 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1906 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001907 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001908 break;
1909 default:
1910 break;
1911 }
Romain Guy54f154a2017-10-24 21:40:32 +01001912 }
1913
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001914 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001915}
1916
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001917// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001918void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1919 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001920 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1921 *outMode = ColorMode::NATIVE;
1922 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001923 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001924 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001925 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001926
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001927 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001928 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001929
Peiyong Lindfde5112018-06-05 10:58:41 -07001930 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001931 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001932 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001933 if (isHdr) {
1934 bestDataSpace = hdrDataSpace;
1935 }
1936
Chia-I Wu0d711262018-05-21 15:19:35 -07001937 RenderIntent intent;
1938 switch (mDisplayColorSetting) {
1939 case DisplayColorSetting::MANAGED:
1940 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001941 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001942 break;
1943 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001944 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001945 break;
1946 default: // vendor display color setting
1947 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1948 break;
1949 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001950
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001951 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001952}
1953
Chia-I Wu30505fb2018-03-26 16:20:31 -07001954void SurfaceFlinger::setUpHWComposer() {
1955 ATRACE_CALL();
1956 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001957
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001958 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001959 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
1960 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1961 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07001962
1963 // If nothing has changed (!dirty), don't recompose.
1964 // If something changed, but we don't currently have any visible layers,
1965 // and didn't when we last did a composition, then skip it this time.
1966 // The second rule does two things:
1967 // - When all layers are removed from a display, we'll emit one black
1968 // frame, then nothing more until we get new layers.
1969 // - When a display is created with a private layer stack, we won't
1970 // emit any black frames until a layer is added to the layer stack.
1971 bool mustRecompose = dirty && !(empty && wasEmpty);
1972
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001973 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001974 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
1975 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07001976
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001977 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001978
1979 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001980 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07001981 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001982 }
1983
Chia-I Wu30505fb2018-03-26 16:20:31 -07001984 // build the h/w work list
1985 if (CC_UNLIKELY(mGeometryInvalid)) {
1986 mGeometryInvalid = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001987 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001988 const auto displayId = display->getId();
1989 if (displayId >= 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001990 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001991 for (size_t i = 0; i < currentLayers.size(); i++) {
1992 const auto& layer = currentLayers[i];
Dominik Laskowski7e045462018-05-30 13:02:02 -07001993 if (!layer->hasHwcLayer(displayId)) {
1994 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1995 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001996 continue;
1997 }
1998 }
1999
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002000 layer->setGeometry(display, i);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002001 if (mDebugDisableHWC || mDebugRegion) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002002 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002003 }
2004 }
2005 }
2006 }
2007 }
2008
Chia-I Wu30505fb2018-03-26 16:20:31 -07002009 // Set the per-frame data
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002010 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002011 const auto displayId = display->getId();
2012 if (displayId < 0) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002013 continue;
2014 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002015
Chia-I Wu28f320b2018-05-03 11:02:56 -07002016 if (mDrawingState.colorMatrixChanged) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002017 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002018 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002019 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002020 displayId, result);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002021 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002022 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu692e0832018-06-05 15:46:58 -07002023 if (layer->isHdrY410()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002024 layer->forceClientComposition(displayId);
Chia-I Wu692e0832018-06-05 15:46:58 -07002025 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2026 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
2027 !display->hasHDR10Support()) {
2028 layer->forceClientComposition(displayId);
2029 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2030 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2031 !display->hasHLGSupport()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002032 layer->forceClientComposition(displayId);
Peiyong Linf59a7192018-04-25 11:19:31 -07002033 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002034
Dominik Laskowski7e045462018-05-30 13:02:02 -07002035 if (layer->getForceClientComposition(displayId)) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002036 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002037 layer->setCompositionType(displayId, HWC2::Composition::Client);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002038 continue;
2039 }
2040
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002041 layer->setPerFrameData(display);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002042 }
2043
2044 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002045 ColorMode colorMode;
2046 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002047 RenderIntent renderIntent;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002048 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
2049 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002050 }
2051 }
2052
Chia-I Wu28f320b2018-05-03 11:02:56 -07002053 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07002054
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002055 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002056 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002057 continue;
2058 }
2059
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002060 status_t result = display->prepareFrame(*getBE().mHwc);
2061 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002062 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002063 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002064}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002065
Mathias Agopiancd60f992012-08-16 16:28:27 -07002066void SurfaceFlinger::doComposition() {
2067 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002068 ALOGV("doComposition");
2069
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002070 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002071 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002072 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002073 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002074 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002075
2076 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002077 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002078
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002079 display->dirtyRegion.clear();
2080 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002081 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002082 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002083 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002084}
2085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002086void SurfaceFlinger::postFramebuffer()
2087{
Mathias Agopian841cde52012-03-01 15:44:37 -08002088 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002089 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002090
Mathias Agopiana44b0412011-10-16 18:46:35 -07002091 const nsecs_t now = systemTime();
2092 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002093
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002094 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002095 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002096 continue;
2097 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002098 const auto displayId = display->getId();
2099 if (displayId >= 0) {
2100 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002101 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002102 display->onSwapBuffersCompleted();
2103 display->makeCurrent();
2104 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002105 // The layer buffer from the previous frame (if any) is released
2106 // by HWC only when the release fence from this frame (if any) is
2107 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002108 auto hwcLayer = layer->getHwcLayer(displayId);
2109 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002110
2111 // If the layer was client composited in the previous frame, we
2112 // need to merge with the previous client target acquire fence.
2113 // Since we do not track that, always merge with the current
2114 // client target acquire fence when it is available, even though
2115 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002116 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002117 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002118 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002119 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002120
David Sodmanb8af7922017-12-21 15:17:55 -08002121 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002122 }
Chia-I Wu83806892017-11-16 10:50:20 -08002123
2124 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002125 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002126 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002127 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002128 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002129 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002130 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002131 }
2132 }
2133
Dominik Laskowski7e045462018-05-30 13:02:02 -07002134 if (displayId >= 0) {
2135 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002136 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002137 }
2138
Mathias Agopiana44b0412011-10-16 18:46:35 -07002139 mLastSwapBufferTime = systemTime() - now;
2140 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002141
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002142 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002143 const auto display = getDefaultDisplayDeviceLocked();
2144 if (display && getHwComposer().isConnected(display->getId())) {
2145 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002146 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2147 logFrameStats();
2148 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002149 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002150}
2151
Mathias Agopian87baae12012-07-31 12:38:26 -07002152void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002153{
Mathias Agopian841cde52012-03-01 15:44:37 -08002154 ATRACE_CALL();
2155
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002156 // here we keep a copy of the drawing state (that is the state that's
2157 // going to be overwritten by handleTransactionLocked()) outside of
2158 // mStateLock so that the side-effects of the State assignment
2159 // don't happen with mStateLock held (which can cause deadlocks).
2160 State drawingState(mDrawingState);
2161
Mathias Agopianca4d3602011-05-19 15:38:14 -07002162 Mutex::Autolock _l(mStateLock);
2163 const nsecs_t now = systemTime();
2164 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002165
Mathias Agopianca4d3602011-05-19 15:38:14 -07002166 // Here we're guaranteed that some transaction flags are set
2167 // so we can call handleTransactionLocked() unconditionally.
2168 // We call getTransactionFlags(), which will also clear the flags,
2169 // with mStateLock held to guarantee that mCurrentState won't change
2170 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002171
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002172 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002173 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002174 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002175
Mathias Agopianca4d3602011-05-19 15:38:14 -07002176 mLastTransactionTime = systemTime() - now;
2177 mDebugInTransaction = 0;
2178 invalidateHwcGeometry();
2179 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002180}
2181
Dominik Laskowski7e045462018-05-30 13:02:02 -07002182DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002183 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002184 // Figure out whether the event is for the primary display or an
2185 // external display by matching the Hwc display id against one for a
2186 // connected display. If we did not find a match, we then check what
2187 // displays are not already connected to determine the type. If we don't
2188 // have a connected primary display, we assume the new display is meant to
2189 // be the primary display, and then if we don't have an external display,
2190 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002191 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2192 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002193 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002194 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002195 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002196 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002197 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002198 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002199 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002200 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002201 return DisplayDevice::DISPLAY_EXTERNAL;
2202 }
2203
2204 return DisplayDevice::DISPLAY_ID_INVALID;
2205}
2206
Lloyd Piqueba04e622017-12-14 17:11:26 -08002207void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2208 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002209 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002210 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002211 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002212 continue;
2213 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002214
2215 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2216 ALOGE("External displays are not supported by the vr hardware composer.");
2217 continue;
2218 }
2219
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002220 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002221 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002222 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002223 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002224 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002225
2226 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002227 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002228 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002229 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002230 DisplayDeviceState info;
2231 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002232 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2233 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002234 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002235 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002236 mInterceptor->saveDisplayCreation(info);
2237 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002238 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002239 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002240
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002241 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002242 if (idx >= 0) {
2243 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002244 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002245 mCurrentState.displays.removeItemsAt(idx);
2246 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002247 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002248 }
2249
2250 processDisplayChangesLocked();
2251 }
2252
2253 mPendingHotplugEvents.clear();
2254}
2255
Lloyd Pique99d3da52018-01-22 17:48:03 -08002256sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002257 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002258 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002259 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002260 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002261
Lloyd Pique99d3da52018-01-22 17:48:03 -08002262 if (hasWideColorDisplay) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002263 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002264 for (ColorMode colorMode : modes) {
2265 switch (colorMode) {
2266 case ColorMode::DISPLAY_P3:
2267 case ColorMode::ADOBE_RGB:
2268 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002269 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002270 break;
2271 default:
2272 break;
2273 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002274
Dominik Laskowski7e045462018-05-30 13:02:02 -07002275 std::vector<RenderIntent> renderIntents =
2276 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002277 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002278 }
2279 }
2280
Peiyong Lin62665892018-04-16 11:07:44 -07002281 HdrCapabilities hdrCapabilities;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002282 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002283
2284 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2285 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2286
2287 /*
2288 * Create our display's surface
2289 */
2290 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2291 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002292 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002293 renderSurface->setNativeWindow(nativeWindow.get());
2294 const int displayWidth = renderSurface->queryWidth();
2295 const int displayHeight = renderSurface->queryHeight();
2296
2297 // Make sure that composition can never be stalled by a virtual display
2298 // consumer that isn't processing buffers fast enough. We have to do this
2299 // in two places:
2300 // * Here, in case the display is composed entirely by HWC.
2301 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2302 // window's swap interval in eglMakeCurrent, so they'll override the
2303 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002304 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002305 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2306 }
2307
2308 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002309 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002310
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002311 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002312 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2313 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2314 displayHeight, hasWideColorGamut, hdrCapabilities,
2315 getHwComposer().getSupportedPerFrameMetadata(displayId),
2316 hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002317
2318 if (maxFrameBufferAcquiredBuffers >= 3) {
2319 nativeWindowSurface->preallocateBuffers();
2320 }
2321
2322 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002323 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2324 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002325 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002326 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002327 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002328 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002329 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002330 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002331 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002332 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002333 display->setLayerStack(state.layerStack);
2334 display->setProjection(state.orientation, state.viewport, state.frame);
2335 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002336
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002337 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002338}
2339
Lloyd Pique347200f2017-12-14 17:00:15 -08002340void SurfaceFlinger::processDisplayChangesLocked() {
2341 // here we take advantage of Vector's copy-on-write semantics to
2342 // improve performance by skipping the transaction entirely when
2343 // know that the lists are identical
2344 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2345 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2346 if (!curr.isIdenticalTo(draw)) {
2347 mVisibleRegionsDirty = true;
2348 const size_t cc = curr.size();
2349 size_t dc = draw.size();
2350
2351 // find the displays that were removed
2352 // (ie: in drawing state but not in current state)
2353 // also handle displays that changed
2354 // (ie: displays that are in both lists)
2355 for (size_t i = 0; i < dc;) {
2356 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2357 if (j < 0) {
2358 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002359 // Call makeCurrent() on the primary display so we can
2360 // be sure that nothing associated with this display
2361 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002362 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2363 defaultDisplay->makeCurrent();
2364 }
2365 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2366 display->disconnect(getHwComposer());
2367 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002368 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2369 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2370 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2371 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2372 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002373 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002374 } else {
2375 // this display is in both lists. see if something changed.
2376 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002377 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002378 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2379 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2380 if (state_binder != draw_binder) {
2381 // changing the surface is like destroying and
2382 // recreating the DisplayDevice, so we just remove it
2383 // from the drawing state, so that it get re-added
2384 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002385 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2386 display->disconnect(getHwComposer());
2387 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002388 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002389 mDrawingState.displays.removeItemsAt(i);
2390 dc--;
2391 // at this point we must loop to the next item
2392 continue;
2393 }
2394
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002395 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002396 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002397 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002398 }
2399 if ((state.orientation != draw[i].orientation) ||
2400 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002401 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002402 }
2403 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002404 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002405 }
2406 }
2407 }
2408 ++i;
2409 }
2410
2411 // find displays that were added
2412 // (ie: in current state but not in drawing state)
2413 for (size_t i = 0; i < cc; i++) {
2414 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2415 const DisplayDeviceState& state(curr[i]);
2416
2417 sp<DisplaySurface> dispSurface;
2418 sp<IGraphicBufferProducer> producer;
2419 sp<IGraphicBufferProducer> bqProducer;
2420 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002421 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002422
Dominik Laskowski7e045462018-05-30 13:02:02 -07002423 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002424 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002425 // Virtual displays without a surface are dormant:
2426 // they have external state (layer stack, projection,
2427 // etc.) but no internal state (i.e. a DisplayDevice).
2428 if (state.surface != nullptr) {
2429 // Allow VR composer to use virtual displays.
2430 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2431 int width = 0;
2432 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2433 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2434 int height = 0;
2435 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2436 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2437 int intFormat = 0;
2438 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2439 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002440 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002441
Dominik Laskowski7e045462018-05-30 13:02:02 -07002442 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2443 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002444 }
2445
2446 // TODO: Plumb requested format back up to consumer
2447
2448 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002449 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002450 bqProducer, bqConsumer,
2451 state.displayName);
2452
2453 dispSurface = vds;
2454 producer = vds;
2455 }
2456 } else {
2457 ALOGE_IF(state.surface != nullptr,
2458 "adding a supported display, but rendering "
2459 "surface is provided (%p), ignoring it",
2460 state.surface.get());
2461
Dominik Laskowski7e045462018-05-30 13:02:02 -07002462 displayId = state.type;
2463 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002464 producer = bqProducer;
2465 }
2466
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002467 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002468 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002469 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002470 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002471 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002472 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002473 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2474 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2475 true);
2476 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2477 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2478 true);
2479 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002480 }
2481 }
2482 }
2483 }
2484 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002485
2486 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002487}
2488
Mathias Agopian87baae12012-07-31 12:38:26 -07002489void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002490{
Dan Stoza7dde5992015-05-22 09:51:44 -07002491 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002492 mCurrentState.traverseInZOrder([](Layer* layer) {
2493 layer->notifyAvailableFrames();
2494 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002495
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496 /*
2497 * Traversal of the children
2498 * (perform the transaction for each of them if needed)
2499 */
2500
Mathias Agopian3559b072012-08-15 13:46:03 -07002501 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002502 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002503 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002504 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002505
2506 const uint32_t flags = layer->doTransaction(0);
2507 if (flags & Layer::eVisibleRegion)
2508 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002509 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002510 }
2511
2512 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002513 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002514 */
2515
Mathias Agopiane57f2922012-08-09 16:29:12 -07002516 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002517 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002518 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002519 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002521 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002522 // The transform hint might have changed for some layers
2523 // (either because a display has changed, or because a layer
2524 // as changed).
2525 //
2526 // Walk through all the layers in currentLayers,
2527 // and update their transform hint.
2528 //
2529 // If a layer is visible only on a single display, then that
2530 // display is used to calculate the hint, otherwise we use the
2531 // default display.
2532 //
2533 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2534 // the hint is set before we acquire a buffer from the surface texture.
2535 //
2536 // NOTE: layer transactions have taken place already, so we use their
2537 // drawing state. However, SurfaceFlinger's own transaction has not
2538 // happened yet, so we must use the current state layer list
2539 // (soon to become the drawing state list).
2540 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002541 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002542 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002543 bool first = true;
2544 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002545 // NOTE: we rely on the fact that layers are sorted by
2546 // layerStack first (so we don't have to traverse the list
2547 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002548 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002549 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002550 currentlayerStack = layerStack;
2551 // figure out if this layerstack is mirrored
2552 // (more than one display) if so, pick the default display,
2553 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002554 hintDisplay = nullptr;
2555 for (const auto& [token, display] : mDisplays) {
2556 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2557 if (hintDisplay) {
2558 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002559 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002560 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002561 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002562 }
2563 }
2564 }
2565 }
Chet Haase91d25932013-04-11 15:24:55 -07002566
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002567 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002568 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2569 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002570
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002571 // could be null when this layer is using a layerStack
2572 // that is not visible on any display. Also can occur at
2573 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002574 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002575 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002576
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002577 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002578 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002579 if (hintDisplay) {
2580 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002581 }
Robert Carr2047fae2016-11-28 14:09:09 -08002582
2583 first = false;
2584 });
Mathias Agopian84300952012-11-21 16:02:13 -08002585 }
2586
2587
Mathias Agopian3559b072012-08-15 13:46:03 -07002588 /*
2589 * Perform our own transaction if needed
2590 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002591
2592 if (mLayersAdded) {
2593 mLayersAdded = false;
2594 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002595 mVisibleRegionsDirty = true;
2596 }
2597
2598 // some layers might have been removed, so
2599 // we need to update the regions they're exposing.
2600 if (mLayersRemoved) {
2601 mLayersRemoved = false;
2602 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002603 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002604 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002605 // this layer is not visible anymore
2606 // TODO: we could traverse the tree from front to back and
2607 // compute the actual visible region
2608 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002609 Region visibleReg;
2610 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002611 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002612 }
Robert Carr2047fae2016-11-28 14:09:09 -08002613 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002614 }
2615
2616 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002617
2618 updateCursorAsync();
2619}
2620
2621void SurfaceFlinger::updateCursorAsync()
2622{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002623 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002624 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002625 continue;
2626 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002627
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002628 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2629 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002630 }
2631 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002632}
2633
2634void SurfaceFlinger::commitTransaction()
2635{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002636 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002637 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002638 for (const auto& l : mLayersPendingRemoval) {
2639 recordBufferingStats(l->getName().string(),
2640 l->getOccupancyHistory(true));
2641 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002642 }
2643 mLayersPendingRemoval.clear();
2644 }
2645
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002646 // If this transaction is part of a window animation then the next frame
2647 // we composite should be considered an animation as well.
2648 mAnimCompositionPending = mAnimTransactionPending;
2649
Mathias Agopian4fec8732012-06-29 14:12:52 -07002650 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002651 // clear the "changed" flags in current state
2652 mCurrentState.colorMatrixChanged = false;
2653
Robert Carr1f0a16a2016-10-24 16:27:39 -07002654 mDrawingState.traverseInZOrder([](Layer* layer) {
2655 layer->commitChildList();
2656 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002657 mTransactionPending = false;
2658 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002659 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660}
2661
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002662void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2663 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002664 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002665 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002666
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002667 Region aboveOpaqueLayers;
2668 Region aboveCoveredLayers;
2669 Region dirty;
2670
Mathias Agopian87baae12012-07-31 12:38:26 -07002671 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002672
Robert Carr2047fae2016-11-28 14:09:09 -08002673 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002674 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002675 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002676
Jesse Hall01e29052013-02-19 16:13:35 -08002677 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002678 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002679 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002680 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002681
Mathias Agopianab028732010-03-16 16:41:46 -07002682 /*
2683 * opaqueRegion: area of a surface that is fully opaque.
2684 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002685 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002686
2687 /*
2688 * visibleRegion: area of a surface that is visible on screen
2689 * and not fully transparent. This is essentially the layer's
2690 * footprint minus the opaque regions above it.
2691 * Areas covered by a translucent surface are considered visible.
2692 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002693 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002694
2695 /*
2696 * coveredRegion: area of a surface that is covered by all
2697 * visible regions above it (which includes the translucent areas).
2698 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002700
Jesse Halla8026d22012-09-25 13:25:04 -07002701 /*
2702 * transparentRegion: area of a surface that is hinted to be completely
2703 * transparent. This is only used to tell when the layer has no visible
2704 * non-transparent regions and can be removed from the layer list. It
2705 * does not affect the visibleRegion of this layer or any layers
2706 * beneath it. The hint may not be correct if apps don't respect the
2707 * SurfaceView restrictions (which, sadly, some don't).
2708 */
2709 Region transparentRegion;
2710
Mathias Agopianab028732010-03-16 16:41:46 -07002711
2712 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002713 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002714 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002715 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002717 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002718 if (!visibleRegion.isEmpty()) {
2719 // Remove the transparent area from the visible region
2720 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002721 if (tr.preserveRects()) {
2722 // transform the transparent region
2723 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002724 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002725 // transformation too complex, can't do the
2726 // transparent region optimization.
2727 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002728 }
Mathias Agopianab028732010-03-16 16:41:46 -07002729 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730
Mathias Agopianab028732010-03-16 16:41:46 -07002731 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002732 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002733 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002734 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2735 // the opaque region is the layer's footprint
2736 opaqueRegion = visibleRegion;
2737 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738 }
2739 }
2740
Robert Carre5f4f692018-01-12 13:12:28 -08002741 if (visibleRegion.isEmpty()) {
2742 layer->clearVisibilityRegions();
2743 return;
2744 }
2745
Mathias Agopianab028732010-03-16 16:41:46 -07002746 // Clip the covered region to the visible region
2747 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2748
2749 // Update aboveCoveredLayers for next (lower) layer
2750 aboveCoveredLayers.orSelf(visibleRegion);
2751
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752 // subtract the opaque region covered by the layers above us
2753 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002754
2755 // compute this layer's dirty region
2756 if (layer->contentDirty) {
2757 // we need to invalidate the whole region
2758 dirty = visibleRegion;
2759 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002760 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761 layer->contentDirty = false;
2762 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002763 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002764 * the exposed region consists of two components:
2765 * 1) what's VISIBLE now and was COVERED before
2766 * 2) what's EXPOSED now less what was EXPOSED before
2767 *
2768 * note that (1) is conservative, we start with the whole
2769 * visible region but only keep what used to be covered by
2770 * something -- which mean it may have been exposed.
2771 *
2772 * (2) handles areas that were not covered by anything but got
2773 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002774 */
Mathias Agopianab028732010-03-16 16:41:46 -07002775 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002776 const Region oldVisibleRegion = layer->visibleRegion;
2777 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002778 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2779 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780 }
2781 dirty.subtractSelf(aboveOpaqueLayers);
2782
2783 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002784 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785
Mathias Agopianab028732010-03-16 16:41:46 -07002786 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002788
Jesse Halla8026d22012-09-25 13:25:04 -07002789 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790 layer->setVisibleRegion(visibleRegion);
2791 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002792 layer->setVisibleNonTransparentRegion(
2793 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002794 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002795
Mathias Agopian87baae12012-07-31 12:38:26 -07002796 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797}
2798
Chia-I Wuab0c3192017-08-01 11:29:00 -07002799void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002800 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002801 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2802 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002803 }
2804 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002805}
2806
Dan Stoza6b9454d2014-11-07 16:00:59 -08002807bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002808{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002809 ALOGV("handlePageFlip");
2810
Brian Andersond6927fb2016-07-23 23:37:30 -07002811 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812
Mathias Agopian4fec8732012-06-29 14:12:52 -07002813 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002814 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002815 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002816
2817 // Store the set of layers that need updates. This set must not change as
2818 // buffers are being latched, as this could result in a deadlock.
2819 // Example: Two producers share the same command stream and:
2820 // 1.) Layer 0 is latched
2821 // 2.) Layer 0 gets a new frame
2822 // 2.) Layer 1 gets a new frame
2823 // 3.) Layer 1 is latched.
2824 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2825 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002826 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002827 if (layer->hasQueuedFrame()) {
2828 frameQueued = true;
2829 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002830 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002831 } else {
2832 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002833 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002834 } else {
2835 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002836 }
Robert Carr2047fae2016-11-28 14:09:09 -08002837 });
2838
Dan Stoza9e56aa02015-11-02 13:00:03 -08002839 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002840 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002841 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002842 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002843 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002844 newDataLatched = true;
2845 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002846 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002847
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002848 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002849
2850 // If we will need to wake up at some time in the future to deal with a
2851 // queued frame that shouldn't be displayed during this vsync period, wake
2852 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002853 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002854 signalLayerUpdate();
2855 }
2856
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002857 // enter boot animation on first buffer latch
2858 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2859 ALOGI("Enter boot animation");
2860 mBootStage = BootStage::BOOTANIMATION;
2861 }
2862
Dan Stoza6b9454d2014-11-07 16:00:59 -08002863 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002864 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865}
2866
Mathias Agopianad456f92011-01-13 17:53:01 -08002867void SurfaceFlinger::invalidateHwcGeometry()
2868{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002869 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002870}
2871
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002872void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2873 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002874 // We only need to actually compose the display if:
2875 // 1) It is being handled by hardware composer, which may need this to
2876 // keep its virtual display state machine in sync, or
2877 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002878 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002879 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002880 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002881 return;
2882 }
2883
Dan Stoza9e56aa02015-11-02 13:00:03 -08002884 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002885 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002886
2887 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002888 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889}
2890
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002891bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002892 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002893
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002894 const Region bounds(display->bounds());
2895 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002896 const auto displayId = display->getId();
2897 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002898 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002899
Chia-I Wu8e50e692018-05-04 10:12:37 -07002900 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002901 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002902
Dan Stoza9e56aa02015-11-02 13:00:03 -08002903 if (hasClientComposition) {
2904 ALOGV("hasClientComposition");
2905
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002906 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002907 if (display->hasWideColorGamut()) {
2908 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002909 }
2910 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002911 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002912 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002913
Dominik Laskowski7e045462018-05-30 13:02:02 -07002914 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002915 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2916 HWC2::Capability::SkipClientColorTransform);
2917
Chia-I Wud49d6692018-06-27 07:17:41 +08002918 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002919 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2920 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002921 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002922 }
2923
Chia-I Wud49d6692018-06-27 07:17:41 +08002924 // The current enhanced saturation matrix is designed to enhance Display P3,
2925 // thus we only apply this matrix when the render intent is not colorimetric
2926 // and the output color space is Display P3.
2927 needsEnhancedColorMatrix =
2928 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2929 outputDataspace == Dataspace::DISPLAY_P3);
2930 if (needsEnhancedColorMatrix) {
2931 colorMatrix *= mEnhancedSaturationMatrix;
2932 }
2933
2934 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002935
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002936 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002937 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002938 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002939 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002940
2941 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002942 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2943 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2944 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002945 }
2946 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002947 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002948
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002949 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002950 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002951 // when using overlays, we assume a fully transparent framebuffer
2952 // NOTE: we could reduce how much we need to clear, for instance
2953 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002954 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002955 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002956 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002957 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002958 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002959 // we're left with the letterbox region
2960 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002961 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002962
2963 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002964 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002965
Mathias Agopianb9494d52012-04-18 02:28:45 -07002966 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002967 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002968 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002969 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002970 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002971 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002972
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002973 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002974 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002975 // scissor on the main display. It should never be needed
2976 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002977 const Rect& bounds = display->getBounds();
2978 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002979 if (scissor != bounds) {
2980 // scissor doesn't match the screen's dimensions, so we
2981 // need to clear everything outside of it and enable
2982 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002983
Mathias Agopianf45c5102012-10-24 16:29:17 -07002984 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002985 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002986 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002987 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002988 }
2989 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002990 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002991
Mathias Agopian85d751c2012-08-29 16:59:24 -07002992 /*
2993 * and then, render the layers targeted at the framebuffer
2994 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002995
Dan Stoza9e56aa02015-11-02 13:00:03 -08002996 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002997 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002998 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002999 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003000 const Region clip(bounds.intersect(
3001 displayTransform.transform(layer->visibleRegion)));
3002 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003003 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003004 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003005 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003006 case HWC2::Composition::Cursor:
3007 case HWC2::Composition::Device:
3008 case HWC2::Composition::Sideband:
3009 case HWC2::Composition::SolidColor: {
3010 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003011 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3012 layer->isOpaque(state) && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003013 // never clear the very first layer since we're
3014 // guaranteed the FB is already cleared
3015 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003016 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003017 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003018 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003019 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003020 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003021 break;
3022 }
3023 default:
3024 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003025 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003026 } else {
3027 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003028 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003029 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003030 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003031
Chia-I Wud49d6692018-06-27 07:17:41 +08003032 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003033 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003034 }
3035
Mathias Agopianf45c5102012-10-24 16:29:17 -07003036 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003037 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003038 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039}
3040
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003041void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3042 const Region& region) const {
3043 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003044 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003045 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003046}
3047
Dan Stoza7d89d062015-04-30 13:29:25 -07003048status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003049 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003050 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003051 const sp<Layer>& lbc,
3052 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003053{
Dan Stoza7d89d062015-04-30 13:29:25 -07003054 // add this layer to the current state list
3055 {
3056 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003057 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003058 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3059 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003060 return NO_MEMORY;
3061 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003062 if (parent == nullptr) {
3063 mCurrentState.layersSortedByZ.add(lbc);
3064 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003065 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003066 ALOGE("addClientLayer called with a removed parent");
3067 return NAME_NOT_FOUND;
3068 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003069 parent->addChild(lbc);
3070 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003071
Yiwei Zhang243b3782018-05-15 17:40:04 -07003072 if (gbc != nullptr) {
3073 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3074 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3075 mMaxGraphicBufferProducerListSize,
3076 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3077 mGraphicBufferProducerList.size(),
3078 mMaxGraphicBufferProducerListSize, mNumLayers);
3079 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003080 mLayersAdded = true;
3081 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003082 }
3083
Mathias Agopian96f08192010-06-02 23:28:45 -07003084 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003085 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003086
Dan Stoza7d89d062015-04-30 13:29:25 -07003087 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003088}
3089
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003090status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003091 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003092 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3093}
Robert Carr7f9b8992017-03-10 11:08:39 -08003094
chaviwca27f252018-02-06 16:46:39 -08003095status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3096 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003097 if (layer->isPendingRemoval()) {
3098 return NO_ERROR;
3099 }
3100
Robert Carr1f0a16a2016-10-24 16:27:39 -07003101 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003102 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003103 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003104 if (topLevelOnly) {
3105 return NO_ERROR;
3106 }
3107
Chia-I Wu98f1c102017-05-30 14:54:08 -07003108 sp<Layer> ancestor = p;
3109 while (ancestor->getParent() != nullptr) {
3110 ancestor = ancestor->getParent();
3111 }
3112 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3113 ALOGE("removeLayer called with a layer whose parent has been removed");
3114 return NAME_NOT_FOUND;
3115 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003116
3117 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003118 } else {
3119 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003120 }
3121
Robert Carr136e2f62017-02-08 17:54:29 -08003122 // As a matter of normal operation, the LayerCleaner will produce a second
3123 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3124 // so we will succeed in promoting it, but it's already been removed
3125 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3126 // otherwise something has gone wrong and we are leaking the layer.
3127 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003128 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3129 layer->getName().string(),
3130 (p != nullptr) ? p->getName().string() : "no-parent");
3131 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003132 } else if (index < 0) {
3133 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003134 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003135
Chia-I Wuc6657022017-08-15 11:18:17 -07003136 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003137 mLayersPendingRemoval.add(layer);
3138 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003139 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003140 setTransactionFlags(eTransactionNeeded);
3141 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142}
3143
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003144uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003145 return android_atomic_release_load(&mTransactionFlags);
3146}
3147
Mathias Agopian3f844832013-08-07 21:24:32 -07003148uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003149 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3150}
3151
Mathias Agopian3f844832013-08-07 21:24:32 -07003152uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003153 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3154}
3155
3156uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3157 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003159 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003161 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162 }
3163 return old;
3164}
3165
chaviwca27f252018-02-06 16:46:39 -08003166bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3167 for (const ComposerState& state : states) {
3168 // Here we need to check that the interface we're given is indeed
3169 // one of our own. A malicious client could give us a nullptr
3170 // IInterface, or one of its own or even one of our own but a
3171 // different type. All these situations would cause us to crash.
3172 if (state.client == nullptr) {
3173 return true;
3174 }
3175
3176 sp<IBinder> binder = IInterface::asBinder(state.client);
3177 if (binder == nullptr) {
3178 return true;
3179 }
3180
3181 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3182 return true;
3183 }
3184 }
3185 return false;
3186}
3187
Mathias Agopian8b33f032012-07-24 20:43:54 -07003188void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003189 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003190 const Vector<DisplayState>& displays,
3191 uint32_t flags)
3192{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003193 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003194 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003195 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003196
chaviwca27f252018-02-06 16:46:39 -08003197 if (containsAnyInvalidClientState(states)) {
3198 return;
3199 }
3200
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003201 if (flags & eAnimation) {
3202 // For window updates that are part of an animation we must wait for
3203 // previous animation "frames" to be handled.
3204 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003205 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003206 if (CC_UNLIKELY(err != NO_ERROR)) {
3207 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003208 // caller after a few seconds.
3209 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3210 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003211 mAnimTransactionPending = false;
3212 break;
3213 }
3214 }
3215 }
3216
chaviwca27f252018-02-06 16:46:39 -08003217 for (const DisplayState& display : displays) {
3218 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003219 }
3220
chaviwca27f252018-02-06 16:46:39 -08003221 for (const ComposerState& state : states) {
3222 transactionFlags |= setClientStateLocked(state);
3223 }
3224
3225 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3226 // as destroyed should only occur after setting all other states. This is to allow for a
3227 // child re-parent to happen before marking its original parent as destroyed (which would
3228 // then mark the child as destroyed).
3229 for (const ComposerState& state : states) {
3230 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003231 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003232
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003233 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3234 // anyway. This can be used as a flush mechanism for previous async transactions.
3235 // Empty animation transaction can be used to simulate back-pressure, so also force a
3236 // transaction for empty animation transactions.
3237 if (transactionFlags == 0 &&
3238 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003239 transactionFlags = eTransactionNeeded;
3240 }
3241
Mathias Agopian386aa982011-11-07 21:58:03 -08003242 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003243 if (mInterceptor->isEnabled()) {
3244 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003245 }
Irvel468051e2016-06-13 16:44:44 -07003246
Mathias Agopian386aa982011-11-07 21:58:03 -08003247 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003248 const auto start = (flags & eEarlyWakeup)
3249 ? VSyncModulator::TransactionStart::EARLY
3250 : VSyncModulator::TransactionStart::NORMAL;
3251 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003252
3253 // if this is a synchronous transaction, wait for it to take effect
3254 // before returning.
3255 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003256 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003257 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003258 if (flags & eAnimation) {
3259 mAnimTransactionPending = true;
3260 }
3261 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003262 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3263 if (CC_UNLIKELY(err != NO_ERROR)) {
3264 // just in case something goes wrong in SF, return to the
3265 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003266 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3267 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003268 break;
3269 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003270 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003271 }
3272}
3273
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003274uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3275 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3276 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003277
Mathias Agopiane57f2922012-08-09 16:29:12 -07003278 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003279 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3280
3281 const uint32_t what = s.what;
3282 if (what & DisplayState::eSurfaceChanged) {
3283 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3284 state.surface = s.surface;
3285 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003286 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003287 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003288 if (what & DisplayState::eLayerStackChanged) {
3289 if (state.layerStack != s.layerStack) {
3290 state.layerStack = s.layerStack;
3291 flags |= eDisplayTransactionNeeded;
3292 }
3293 }
3294 if (what & DisplayState::eDisplayProjectionChanged) {
3295 if (state.orientation != s.orientation) {
3296 state.orientation = s.orientation;
3297 flags |= eDisplayTransactionNeeded;
3298 }
3299 if (state.frame != s.frame) {
3300 state.frame = s.frame;
3301 flags |= eDisplayTransactionNeeded;
3302 }
3303 if (state.viewport != s.viewport) {
3304 state.viewport = s.viewport;
3305 flags |= eDisplayTransactionNeeded;
3306 }
3307 }
3308 if (what & DisplayState::eDisplaySizeChanged) {
3309 if (state.width != s.width) {
3310 state.width = s.width;
3311 flags |= eDisplayTransactionNeeded;
3312 }
3313 if (state.height != s.height) {
3314 state.height = s.height;
3315 flags |= eDisplayTransactionNeeded;
3316 }
3317 }
3318
Mathias Agopiane57f2922012-08-09 16:29:12 -07003319 return flags;
3320}
3321
Robert Carrd4ae7f32018-06-07 16:10:57 -07003322bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3323 IPCThreadState* ipc = IPCThreadState::self();
3324 const int pid = ipc->getCallingPid();
3325 const int uid = ipc->getCallingUid();
3326
3327 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3328 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3329 return false;
3330 }
3331 return true;
3332}
3333
chaviwca27f252018-02-06 16:46:39 -08003334uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3335 const layer_state_t& s = composerState.state;
3336 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3337
Mathias Agopian13127d82013-03-05 17:47:11 -08003338 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003339 if (layer == nullptr) {
3340 return 0;
3341 }
3342
3343 if (layer->isPendingRemoval()) {
3344 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3345 return 0;
3346 }
3347
3348 uint32_t flags = 0;
3349
3350 const uint32_t what = s.what;
3351 bool geometryAppliesWithResize =
3352 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003353
3354 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3355 // pending state will also be deferred.
3356 if (what & layer_state_t::eDeferTransaction) {
3357 layer->pushPendingState();
3358 }
3359
chaviw8b3871a2017-11-01 17:41:01 -07003360 if (what & layer_state_t::ePositionChanged) {
3361 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3362 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003363 }
chaviw8b3871a2017-11-01 17:41:01 -07003364 }
3365 if (what & layer_state_t::eLayerChanged) {
3366 // NOTE: index needs to be calculated before we update the state
3367 const auto& p = layer->getParent();
3368 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003369 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003370 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003371 mCurrentState.layersSortedByZ.removeAt(idx);
3372 mCurrentState.layersSortedByZ.add(layer);
3373 // we need traversal (state changed)
3374 // AND transaction (list changed)
3375 flags |= eTransactionNeeded|eTraversalNeeded;
3376 }
chaviw8b3871a2017-11-01 17:41:01 -07003377 } else {
3378 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003379 flags |= eTransactionNeeded|eTraversalNeeded;
3380 }
3381 }
chaviw8b3871a2017-11-01 17:41:01 -07003382 }
3383 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003384 // NOTE: index needs to be calculated before we update the state
3385 const auto& p = layer->getParent();
3386 if (p == nullptr) {
3387 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3388 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3389 mCurrentState.layersSortedByZ.removeAt(idx);
3390 mCurrentState.layersSortedByZ.add(layer);
3391 // we need traversal (state changed)
3392 // AND transaction (list changed)
3393 flags |= eTransactionNeeded|eTraversalNeeded;
3394 }
3395 } else {
3396 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3397 flags |= eTransactionNeeded|eTraversalNeeded;
3398 }
chaviw8b3871a2017-11-01 17:41:01 -07003399 }
3400 }
3401 if (what & layer_state_t::eSizeChanged) {
3402 if (layer->setSize(s.w, s.h)) {
3403 flags |= eTraversalNeeded;
3404 }
3405 }
3406 if (what & layer_state_t::eAlphaChanged) {
3407 if (layer->setAlpha(s.alpha))
3408 flags |= eTraversalNeeded;
3409 }
3410 if (what & layer_state_t::eColorChanged) {
3411 if (layer->setColor(s.color))
3412 flags |= eTraversalNeeded;
3413 }
3414 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003415 // TODO: b/109894387
3416 //
3417 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3418 // rotation. To see the problem observe that if we have a square parent, and a child
3419 // of the same size, then we rotate the child 45 degrees around it's center, the child
3420 // must now be cropped to a non rectangular 8 sided region.
3421 //
3422 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3423 // private API, and the WindowManager only uses rotation in one case, which is on a top
3424 // level layer in which cropping is not an issue.
3425 //
3426 // However given that abuse of rotation matrices could lead to surfaces extending outside
3427 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3428 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3429 // transformations.
3430 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003431 flags |= eTraversalNeeded;
3432 }
3433 if (what & layer_state_t::eTransparentRegionChanged) {
3434 if (layer->setTransparentRegionHint(s.transparentRegion))
3435 flags |= eTraversalNeeded;
3436 }
3437 if (what & layer_state_t::eFlagsChanged) {
3438 if (layer->setFlags(s.flags, s.mask))
3439 flags |= eTraversalNeeded;
3440 }
3441 if (what & layer_state_t::eCropChanged) {
3442 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3443 flags |= eTraversalNeeded;
3444 }
3445 if (what & layer_state_t::eFinalCropChanged) {
3446 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3447 flags |= eTraversalNeeded;
3448 }
3449 if (what & layer_state_t::eLayerStackChanged) {
3450 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3451 // We only allow setting layer stacks for top level layers,
3452 // everything else inherits layer stack from its parent.
3453 if (layer->hasParent()) {
3454 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3455 layer->getName().string());
3456 } else if (idx < 0) {
3457 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3458 "that also does not appear in the top level layer list. Something"
3459 " has gone wrong.", layer->getName().string());
3460 } else if (layer->setLayerStack(s.layerStack)) {
3461 mCurrentState.layersSortedByZ.removeAt(idx);
3462 mCurrentState.layersSortedByZ.add(layer);
3463 // we need traversal (state changed)
3464 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003465 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003466 }
3467 }
3468 if (what & layer_state_t::eDeferTransaction) {
3469 if (s.barrierHandle != nullptr) {
3470 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3471 } else if (s.barrierGbp != nullptr) {
3472 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3473 if (authenticateSurfaceTextureLocked(gbp)) {
3474 const auto& otherLayer =
3475 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3476 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3477 } else {
3478 ALOGE("Attempt to defer transaction to to an"
3479 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003480 }
3481 }
chaviw8b3871a2017-11-01 17:41:01 -07003482 // We don't trigger a traversal here because if no other state is
3483 // changed, we don't want this to cause any more work
3484 }
3485 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003486 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003487 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003488 if (!hadParent) {
3489 mCurrentState.layersSortedByZ.remove(layer);
3490 }
chaviw8b3871a2017-11-01 17:41:01 -07003491 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003492 }
chaviw8b3871a2017-11-01 17:41:01 -07003493 }
3494 if (what & layer_state_t::eReparentChildren) {
3495 if (layer->reparentChildren(s.reparentHandle)) {
3496 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003497 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003498 }
chaviw8b3871a2017-11-01 17:41:01 -07003499 if (what & layer_state_t::eDetachChildren) {
3500 layer->detachChildren();
3501 }
3502 if (what & layer_state_t::eOverrideScalingModeChanged) {
3503 layer->setOverrideScalingMode(s.overrideScalingMode);
3504 // We don't trigger a traversal here because if no other state is
3505 // changed, we don't want this to cause any more work
3506 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003507 return flags;
3508}
3509
chaviwca27f252018-02-06 16:46:39 -08003510void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3511 const layer_state_t& state = composerState.state;
3512 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3513
3514 sp<Layer> layer(client->getLayerUser(state.surface));
3515 if (layer == nullptr) {
3516 return;
3517 }
3518
3519 if (layer->isPendingRemoval()) {
3520 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3521 return;
3522 }
3523
3524 if (state.what & layer_state_t::eDestroySurface) {
3525 removeLayerLocked(mStateLock, layer);
3526 }
3527}
3528
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003529status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003530 const String8& name,
3531 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003532 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003533 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003534 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003535{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003536 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003537 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003538 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003539 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003540 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003541
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003542 status_t result = NO_ERROR;
3543
3544 sp<Layer> layer;
3545
Cody Northropbc755282017-03-31 12:00:08 -06003546 String8 uniqueName = getUniqueLayerName(name);
3547
Mathias Agopian3165cc22012-08-08 19:42:09 -07003548 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3549 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003550 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003551 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003552 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003553
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003554 break;
chaviw13fdc492017-06-27 12:40:18 -07003555 case ISurfaceComposerClient::eFXSurfaceColor:
3556 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003557 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003558 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003559 break;
3560 default:
3561 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003562 break;
3563 }
3564
Dan Stoza7d89d062015-04-30 13:29:25 -07003565 if (result != NO_ERROR) {
3566 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003567 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003568
Chia-I Wuab0c3192017-08-01 11:29:00 -07003569 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3570 // TODO b/64227542
3571 if (windowType == 441731) {
3572 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3573 layer->setPrimaryDisplayOnly();
3574 }
3575
Albert Chaulk479c60c2017-01-27 14:21:34 -05003576 layer->setInfo(windowType, ownerUid);
3577
Robert Carr1f0a16a2016-10-24 16:27:39 -07003578 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003579 if (result != NO_ERROR) {
3580 return result;
3581 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003582 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003583
3584 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003585 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003586}
3587
Cody Northropbc755282017-03-31 12:00:08 -06003588String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3589{
3590 bool matchFound = true;
3591 uint32_t dupeCounter = 0;
3592
3593 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3594 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3595
Dan Stoza436ccf32018-06-21 12:10:12 -07003596 // Grab the state lock since we're accessing mCurrentState
3597 Mutex::Autolock lock(mStateLock);
3598
Cody Northropbc755282017-03-31 12:00:08 -06003599 // Loop over layers until we're sure there is no matching name
3600 while (matchFound) {
3601 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003602 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003603 if (layer->getName() == uniqueName) {
3604 matchFound = true;
3605 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3606 }
3607 });
3608 }
3609
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003610 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3611 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003612
3613 return uniqueName;
3614}
3615
David Sodman0c69cad2017-08-21 12:12:51 -07003616status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003617 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3618 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619{
3620 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003621 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003622 case PIXEL_FORMAT_TRANSPARENT:
3623 case PIXEL_FORMAT_TRANSLUCENT:
3624 format = PIXEL_FORMAT_RGBA_8888;
3625 break;
3626 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003627 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628 break;
3629 }
3630
David Sodman0c69cad2017-08-21 12:12:51 -07003631 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3632 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003633 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003634 *handle = layer->getHandle();
3635 *gbp = layer->getProducer();
3636 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003637 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003638
David Sodman0c69cad2017-08-21 12:12:51 -07003639 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003640 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003641}
3642
chaviw13fdc492017-06-27 12:40:18 -07003643status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003644 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003645 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003646{
chaviw13fdc492017-06-27 12:40:18 -07003647 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003648 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003649 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003650}
3651
Mathias Agopianac9fa422013-02-11 16:40:36 -08003652status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003653{
Robert Carr9524cb32017-02-13 11:32:32 -08003654 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003655 status_t err = NO_ERROR;
3656 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003657 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003658 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003659 err = removeLayer(l);
3660 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3661 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003662 }
3663 return err;
3664}
3665
Mathias Agopian13127d82013-03-05 17:47:11 -08003666status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003667{
Mathias Agopian67106042013-03-14 19:18:13 -07003668 // called by ~LayerCleaner() when all references to the IBinder (handle)
3669 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003670 sp<Layer> l = layer.promote();
3671 if (l == nullptr) {
3672 // The layer has already been removed, carry on
3673 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003674 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003675 // If we have a parent, then we can continue to live as long as it does.
3676 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003677}
3678
Mathias Agopianb60314a2012-04-10 22:09:54 -07003679// ---------------------------------------------------------------------------
3680
Andy McFadden13a082e2012-08-24 10:16:42 -07003681void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003682 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3683 if (!displayToken) return;
3684
Jesse Hall01e29052013-02-19 16:13:35 -08003685 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003686 Vector<ComposerState> state;
3687 Vector<DisplayState> displays;
3688 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003689 d.what = DisplayState::eDisplayProjectionChanged |
3690 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003691 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003692 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003693 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003694 d.frame.makeInvalid();
3695 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003696 d.width = 0;
3697 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003698 displays.add(d);
3699 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003700
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003701 const auto display = getDisplayDevice(displayToken);
3702 if (!display) return;
3703
3704 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3705
3706 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003707 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003708 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003709
Brian Andersond0010582017-03-07 13:20:31 -08003710 // Use phase of 0 since phase is not known.
3711 // Use latency of 0, which will snap to the ideal latency.
3712 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003713}
3714
3715void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003716 // Async since we may be called from the main thread.
3717 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003718}
3719
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003720void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3721 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003722 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003723 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003724
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003725 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003726 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003727 return;
3728 }
3729
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003730 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003731 ALOGW("Trying to set power mode for virtual display");
3732 return;
3733 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003734
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003735 display->setPowerMode(mode);
3736
Lloyd Pique4dccc412018-01-22 17:21:36 -08003737 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003738 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003739 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003740 if (idx < 0) {
3741 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3742 return;
3743 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003744 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003745 }
3746
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003747 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003748 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003749 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003750 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003751 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003752 // FIXME: eventthread only knows about the main display right now
3753 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003754 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003755 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003756
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003757 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003758 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003759 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003760
3761 struct sched_param param = {0};
3762 param.sched_priority = 1;
3763 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3764 ALOGW("Couldn't set SCHED_FIFO on display on");
3765 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003766 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003767 // Turn off the display
3768 struct sched_param param = {0};
3769 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3770 ALOGW("Couldn't set SCHED_OTHER on display off");
3771 }
3772
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003773 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003774 disableHardwareVsync(true); // also cancels any in-progress resync
3775
Mathias Agopiancde87a32012-09-13 14:09:01 -07003776 // FIXME: eventthread only knows about the main display right now
3777 mEventThread->onScreenReleased();
3778 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003779
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003780 getHwComposer().setPowerMode(type, mode);
3781 mVisibleRegionsDirty = true;
3782 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003783 } else if (mode == HWC_POWER_MODE_DOZE ||
3784 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003785 // Update display while dozing
3786 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003787 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003788 // FIXME: eventthread only knows about the main display right now
3789 mEventThread->onScreenAcquired();
3790 resyncToHardwareVsync(true);
3791 }
3792 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3793 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003794 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003795 disableHardwareVsync(true); // also cancels any in-progress resync
3796 // FIXME: eventthread only knows about the main display right now
3797 mEventThread->onScreenReleased();
3798 }
3799 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003800 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003801 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003802 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003803 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003804
3805 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003806}
3807
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003808void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003809 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003810 const auto display = getDisplayDevice(displayToken);
3811 if (!display) {
3812 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3813 displayToken.get());
3814 } else if (display->isVirtual()) {
3815 ALOGW("Attempt to set power mode %d for virtual display", mode);
3816 } else {
3817 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003818 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003819 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003820}
3821
3822// ---------------------------------------------------------------------------
3823
Lloyd Pique755e3192018-01-31 16:46:15 -08003824status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3825 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003826 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003827
Mathias Agopianbd115332013-04-18 16:41:04 -07003828 IPCThreadState* ipc = IPCThreadState::self();
3829 const int pid = ipc->getCallingPid();
3830 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003831
Mathias Agopianbd115332013-04-18 16:41:04 -07003832 if ((uid != AID_SHELL) &&
3833 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003834 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003835 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003836 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003837 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003838 // (this would indicate SF is stuck, but we want to be able to
3839 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003840 status_t err = mStateLock.timedLock(s2ns(1));
3841 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003842 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003843 result.appendFormat(
3844 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3845 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003846 }
3847
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003848 bool dumpAll = true;
3849 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003850 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003851
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003852 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003853 if ((index < numArgs) &&
3854 (args[index] == String16("--list"))) {
3855 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003856 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003857 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003858 }
3859
3860 if ((index < numArgs) &&
3861 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003862 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003863 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003864 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003865 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003866
3867 if ((index < numArgs) &&
3868 (args[index] == String16("--latency-clear"))) {
3869 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003870 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003871 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003872 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003873
3874 if ((index < numArgs) &&
3875 (args[index] == String16("--dispsync"))) {
3876 index++;
3877 mPrimaryDispSync.dump(result);
3878 dumpAll = false;
3879 }
Dan Stozab90cf072015-03-05 11:05:59 -08003880
3881 if ((index < numArgs) &&
3882 (args[index] == String16("--static-screen"))) {
3883 index++;
3884 dumpStaticScreenStats(result);
3885 dumpAll = false;
3886 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003887
3888 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003889 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003890 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003891 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003892 dumpAll = false;
3893 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003894
3895 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3896 index++;
3897 dumpWideColorInfo(result);
3898 dumpAll = false;
3899 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003900
3901 if ((index < numArgs) &&
3902 (args[index] == String16("--enable-layer-stats"))) {
3903 index++;
3904 mLayerStats.enable();
3905 dumpAll = false;
3906 }
3907
3908 if ((index < numArgs) &&
3909 (args[index] == String16("--disable-layer-stats"))) {
3910 index++;
3911 mLayerStats.disable();
3912 dumpAll = false;
3913 }
3914
3915 if ((index < numArgs) &&
3916 (args[index] == String16("--clear-layer-stats"))) {
3917 index++;
3918 mLayerStats.clear();
3919 dumpAll = false;
3920 }
3921
3922 if ((index < numArgs) &&
3923 (args[index] == String16("--dump-layer-stats"))) {
3924 index++;
3925 mLayerStats.dump(result);
3926 dumpAll = false;
3927 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003928
3929 if ((index < numArgs) &&
3930 (args[index] == String16("--display-identification"))) {
3931 index++;
3932 dumpDisplayIdentificationData(result);
3933 dumpAll = false;
3934 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003935
3936 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3937 index++;
3938 mTimeStats.parseArgs(asProto, args, index, result);
3939 dumpAll = false;
3940 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003941 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003942
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003943 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003944 if (asProto) {
3945 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3946 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3947 } else {
3948 dumpAllLocked(args, index, result);
3949 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003950 }
3951
Mathias Agopian9795c422009-08-26 16:36:26 -07003952 if (locked) {
3953 mStateLock.unlock();
3954 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003955 }
3956 write(fd, result.string(), result.size());
3957 return NO_ERROR;
3958}
3959
Dan Stozac7014012014-02-14 15:03:43 -08003960void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3961 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003962{
Robert Carr2047fae2016-11-28 14:09:09 -08003963 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003964 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003965 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003966}
3967
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003968void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003969 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003970{
3971 String8 name;
3972 if (index < args.size()) {
3973 name = String8(args[index]);
3974 index++;
3975 }
3976
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003977 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3978 getHwComposer().isConnected(displayId)) {
3979 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3980 const nsecs_t period = activeConfig->getVsyncPeriod();
3981 result.appendFormat("%" PRId64 "\n", period);
3982 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003983
3984 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003985 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003986 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003987 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003988 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003989 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003990 }
Robert Carr2047fae2016-11-28 14:09:09 -08003991 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003992 }
3993}
3994
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003995void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003996 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003997{
3998 String8 name;
3999 if (index < args.size()) {
4000 name = String8(args[index]);
4001 index++;
4002 }
4003
Robert Carr2047fae2016-11-28 14:09:09 -08004004 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004005 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004006 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004007 }
Robert Carr2047fae2016-11-28 14:09:09 -08004008 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004009
Svetoslavd85084b2014-03-20 10:28:31 -07004010 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004011}
4012
Jamie Gennis6547ff42013-07-16 20:12:42 -07004013// This should only be called from the main thread. Otherwise it would need
4014// the lock and should use mCurrentState rather than mDrawingState.
4015void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004016 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004017 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004018 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004019
4020 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4021}
4022
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004023void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004024{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004025 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004026
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004027 if (isLayerTripleBufferingDisabled())
4028 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004029
4030 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004031 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004032 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004033 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004034 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4035 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004036 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004037}
4038
Dan Stozab90cf072015-03-05 11:05:59 -08004039void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4040{
4041 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004042 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4043 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004044 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004045 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004046 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4047 b + 1, bucketTimeSec, percent);
4048 }
David Sodman4a36e932017-11-07 14:29:47 -08004049 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004050 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004051 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004052 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004053 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004054}
4055
Dan Stozae77c7662016-05-13 11:37:28 -07004056void SurfaceFlinger::recordBufferingStats(const char* layerName,
4057 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004058 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4059 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004060 for (const auto& segment : history) {
4061 if (!segment.usedThirdBuffer) {
4062 stats.twoBufferTime += segment.totalTime;
4063 }
4064 if (segment.occupancyAverage < 1.0f) {
4065 stats.doubleBufferedTime += segment.totalTime;
4066 } else if (segment.occupancyAverage < 2.0f) {
4067 stats.tripleBufferedTime += segment.totalTime;
4068 }
4069 ++stats.numSegments;
4070 stats.totalTime += segment.totalTime;
4071 }
4072}
4073
Brian Andersond6927fb2016-07-23 23:37:30 -07004074void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4075 result.appendFormat("Layer frame timestamps:\n");
4076
4077 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4078 const size_t count = currentLayers.size();
4079 for (size_t i=0 ; i<count ; i++) {
4080 currentLayers[i]->dumpFrameEvents(result);
4081 }
4082}
4083
Dan Stozae77c7662016-05-13 11:37:28 -07004084void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4085 result.append("Buffering stats:\n");
4086 result.append(" [Layer name] <Active time> <Two buffer> "
4087 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004088 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004089 typedef std::tuple<std::string, float, float, float> BufferTuple;
4090 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004091 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004092 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004093 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004094 if (stats.numSegments == 0) {
4095 continue;
4096 }
4097 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4098 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4099 stats.totalTime;
4100 float doubleBufferRatio = static_cast<float>(
4101 stats.doubleBufferedTime) / stats.totalTime;
4102 float tripleBufferRatio = static_cast<float>(
4103 stats.tripleBufferedTime) / stats.totalTime;
4104 sorted.insert({activeTime, {name, twoBufferRatio,
4105 doubleBufferRatio, tripleBufferRatio}});
4106 }
4107 for (const auto& sortedPair : sorted) {
4108 float activeTime = sortedPair.first;
4109 const BufferTuple& values = sortedPair.second;
4110 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4111 std::get<0>(values).c_str(), activeTime,
4112 std::get<1>(values), std::get<2>(values),
4113 std::get<3>(values));
4114 }
4115 result.append("\n");
4116}
4117
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004118void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004119 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004120 const int32_t displayId = display->getId();
4121 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4122 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004123 continue;
4124 }
4125
Dominik Laskowski7e045462018-05-30 13:02:02 -07004126 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004127 uint8_t port;
4128 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004129 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004130 result.append("no identification data\n");
4131 continue;
4132 }
4133
4134 if (!isEdid(data)) {
4135 result.append("unknown identification data: ");
4136 for (uint8_t byte : data) {
4137 result.appendFormat("%x ", byte);
4138 }
4139 result.append("\n");
4140 continue;
4141 }
4142
4143 const auto edid = parseEdid(data);
4144 if (!edid) {
4145 result.append("invalid EDID: ");
4146 for (uint8_t byte : data) {
4147 result.appendFormat("%x ", byte);
4148 }
4149 result.append("\n");
4150 continue;
4151 }
4152
4153 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4154 result.append(edid->displayName.data(), edid->displayName.length());
4155 result.append("\"\n");
4156 }
4157 result.append("\n");
4158}
4159
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004160void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4161 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004162 result.appendFormat("DisplayColorSetting: %s\n",
4163 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004164
4165 // TODO: print out if wide-color mode is active or not
4166
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004167 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004168 const int32_t displayId = display->getId();
4169 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004170 continue;
4171 }
4172
Dominik Laskowski7e045462018-05-30 13:02:02 -07004173 result.appendFormat("Display %d color modes:\n", displayId);
4174 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004175 for (auto&& mode : modes) {
4176 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4177 }
4178
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004179 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004180 result.appendFormat(" Current color mode: %s (%d)\n",
4181 decodeColorMode(currentMode).c_str(), currentMode);
4182 }
4183 result.append("\n");
4184}
4185
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004186LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004187 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004188 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4189 const State& state = useDrawing ? mDrawingState : mCurrentState;
4190 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004191 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004192 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004193 });
4194
4195 return layersProto;
4196}
4197
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004198LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004199 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004200
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004201 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004202 resolution->set_w(display.getWidth());
4203 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004204
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004205 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4206 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4207 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004208
Dominik Laskowski7e045462018-05-30 13:02:02 -07004209 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004210 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004211 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004212 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004213 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004214 }
4215 });
4216
4217 return layersProto;
4218}
4219
Mathias Agopian74d211a2013-04-22 16:55:35 +02004220void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4221 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004222{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004223 bool colorize = false;
4224 if (index < args.size()
4225 && (args[index] == String16("--color"))) {
4226 colorize = true;
4227 index++;
4228 }
4229
4230 Colorizer colorizer(colorize);
4231
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004232 // figure out if we're stuck somewhere
4233 const nsecs_t now = systemTime();
4234 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4235 const nsecs_t inTransaction(mDebugInTransaction);
4236 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4237 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4238
4239 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004240 * Dump library configuration.
4241 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004242
4243 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004244 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004245 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004246 appendSfConfigString(result);
4247 appendUiConfigString(result);
4248 appendGuiConfigString(result);
4249 result.append("\n");
4250
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004251 result.append("\nDisplay identification data:\n");
4252 dumpDisplayIdentificationData(result);
4253
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004254 result.append("\nWide-Color information:\n");
4255 dumpWideColorInfo(result);
4256
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004257 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004258 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004259 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004260 result.append(SyncFeatures::getInstance().toString());
4261 result.append("\n");
4262
Andy McFadden41d67d72014-04-25 16:58:34 -07004263 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004264 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004265 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004266
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004267 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4268 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004269 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4270 getHwComposer().isConnected(displayId)) {
4271 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004272 result.appendFormat("Display %d: "
4273 "app phase %" PRId64 " ns, "
4274 "sf phase %" PRId64 " ns, "
4275 "early app phase %" PRId64 " ns, "
4276 "early sf phase %" PRId64 " ns, "
4277 "early app gl phase %" PRId64 " ns, "
4278 "early sf gl phase %" PRId64 " ns, "
4279 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4280 displayId,
4281 vsyncPhaseOffsetNs,
4282 sfVsyncPhaseOffsetNs,
4283 appEarlyOffset,
4284 sfEarlyOffset,
4285 appEarlyGlOffset,
4286 sfEarlyOffset,
4287 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004288 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004289 result.append("\n");
4290
Dan Stozab90cf072015-03-05 11:05:59 -08004291 // Dump static screen stats
4292 result.append("\n");
4293 dumpStaticScreenStats(result);
4294 result.append("\n");
4295
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004296 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4297
Dan Stozae77c7662016-05-13 11:37:28 -07004298 dumpBufferingStats(result);
4299
Andy McFadden4803b742012-09-24 19:07:20 -07004300 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004301 * Dump the visible layer list
4302 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004303 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004304 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004305 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4306 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004307 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004308
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004309 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004310 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004311 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004312 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004313
4314 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004315 * Dump Display state
4316 */
4317
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004318 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004319 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004320 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004321 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004322 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004323 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004324 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004325
4326 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004327 * Dump SurfaceFlinger global state
4328 */
4329
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004330 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004331 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004332 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333
Mathias Agopian888c8222012-08-04 21:10:38 -07004334 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004335 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004336
David Sodmanbc815282017-11-05 18:57:52 -08004337 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004338
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004339 if (display) {
4340 display->undefinedRegion.dump(result, "undefinedRegion");
4341 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4342 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004343 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004344 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4345 " last transaction time : %f us\n"
4346 " transaction-flags : %08x\n"
4347 " gpu_to_cpu_unsupported : %d\n",
4348 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4349 mTransactionFlags, !mGpuToCpuSupported);
4350
4351 if (display) {
4352 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4353 result.appendFormat(" refresh-rate : %f fps\n"
4354 " x-dpi : %f\n"
4355 " y-dpi : %f\n",
4356 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4357 activeConfig->getDpiY());
4358 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004359
Mathias Agopian74d211a2013-04-22 16:55:35 +02004360 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004361 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004362
Mathias Agopian74d211a2013-04-22 16:55:35 +02004363 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004364 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004365
4366 /*
4367 * VSYNC state
4368 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004369 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004370 result.append("\n");
4371
4372 /*
4373 * HWC layer minidump
4374 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004375 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004376 const int32_t displayId = display->getId();
4377 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004378 continue;
4379 }
4380
Dominik Laskowski7e045462018-05-30 13:02:02 -07004381 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004382 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004383 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004384 result.append("\n");
4385 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004386
4387 /*
4388 * Dump HWComposer state
4389 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004390 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004391 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004392 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004393 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004394 result.appendFormat(" h/w composer %s\n",
4395 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004396 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004397
4398 /*
4399 * Dump gralloc state
4400 */
4401 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4402 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004403
4404 /*
4405 * Dump VrFlinger state if in use.
4406 */
4407 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4408 result.append("VrFlinger state:\n");
4409 result.append(mVrFlinger->Dump().c_str());
4410 result.append("\n");
4411 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004412}
4413
Dominik Laskowski7e045462018-05-30 13:02:02 -07004414const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004415 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004416 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004417 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004418 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004419 }
4420 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004421
4422 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4423 static const Vector<sp<Layer>> empty;
4424 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004425}
4426
Keun young Park63f165f2012-08-31 10:53:36 -07004427bool SurfaceFlinger::startDdmConnection()
4428{
4429 void* libddmconnection_dso =
4430 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4431 if (!libddmconnection_dso) {
4432 return false;
4433 }
4434 void (*DdmConnection_start)(const char* name);
4435 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004436 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004437 if (!DdmConnection_start) {
4438 dlclose(libddmconnection_dso);
4439 return false;
4440 }
4441 (*DdmConnection_start)(getServiceName());
4442 return true;
4443}
4444
Chia-I Wu28f320b2018-05-03 11:02:56 -07004445void SurfaceFlinger::updateColorMatrixLocked() {
4446 mat4 colorMatrix;
4447 if (mGlobalSaturationFactor != 1.0f) {
4448 // Rec.709 luma coefficients
4449 float3 luminance{0.213f, 0.715f, 0.072f};
4450 luminance *= 1.0f - mGlobalSaturationFactor;
4451 mat4 saturationMatrix = mat4(
4452 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4453 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4454 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4455 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4456 );
4457 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4458 } else {
4459 colorMatrix = mClientColorMatrix * mDaltonizer();
4460 }
4461
4462 if (mCurrentState.colorMatrix != colorMatrix) {
4463 mCurrentState.colorMatrix = colorMatrix;
4464 mCurrentState.colorMatrixChanged = true;
4465 setTransactionFlags(eTransactionNeeded);
4466 }
4467}
4468
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004469status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004470 switch (code) {
4471 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004472 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004473 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004474 case CLEAR_ANIMATION_FRAME_STATS:
4475 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004476 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004477 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004478 case ENABLE_VSYNC_INJECTIONS:
4479 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004480 {
4481 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004482 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4483 IPCThreadState* ipc = IPCThreadState::self();
4484 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4485 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004486 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004487 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004488 break;
4489 }
Robert Carr1db73f62016-12-21 12:58:51 -08004490 /*
4491 * Calling setTransactionState is safe, because you need to have been
4492 * granted a reference to Client* and Handle* to do anything with it.
4493 *
4494 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4495 */
4496 case SET_TRANSACTION_STATE:
4497 case CREATE_SCOPED_CONNECTION:
4498 {
4499 return OK;
4500 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004501 case CAPTURE_SCREEN:
4502 {
4503 // codes that require permission check
4504 IPCThreadState* ipc = IPCThreadState::self();
4505 const int pid = ipc->getCallingPid();
4506 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004507 if ((uid != AID_GRAPHICS) &&
4508 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004509 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004510 return PERMISSION_DENIED;
4511 }
4512 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004513 }
chaviwa76b2712017-09-20 12:02:26 -07004514 case CAPTURE_LAYERS: {
4515 IPCThreadState* ipc = IPCThreadState::self();
4516 const int pid = ipc->getCallingPid();
4517 const int uid = ipc->getCallingUid();
4518 if ((uid != AID_GRAPHICS) &&
4519 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4520 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4521 return PERMISSION_DENIED;
4522 }
4523 break;
4524 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004525 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004526 return OK;
4527}
4528
4529status_t SurfaceFlinger::onTransact(
4530 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4531{
4532 status_t credentialCheck = CheckTransactCodeCredentials(code);
4533 if (credentialCheck != OK) {
4534 return credentialCheck;
4535 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004536
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004537 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4538 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004539 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004540 IPCThreadState* ipc = IPCThreadState::self();
4541 const int uid = ipc->getCallingUid();
4542 if (CC_UNLIKELY(uid != AID_SYSTEM
4543 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004544 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004545 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004546 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004547 return PERMISSION_DENIED;
4548 }
4549 int n;
4550 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004551 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004552 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004553 return NO_ERROR;
4554 case 1002: // SHOW_UPDATES
4555 n = data.readInt32();
4556 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004557 invalidateHwcGeometry();
4558 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004559 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004560 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004561 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004562 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004563 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004564 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004565 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004566 setTransactionFlags(
4567 eTransactionNeeded|
4568 eDisplayTransactionNeeded|
4569 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004570 return NO_ERROR;
4571 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004572 case 1006:{ // send empty update
4573 signalRefresh();
4574 return NO_ERROR;
4575 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004576 case 1008: // toggle use of hw composer
4577 n = data.readInt32();
4578 mDebugDisableHWC = n ? 1 : 0;
4579 invalidateHwcGeometry();
4580 repaintEverything();
4581 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004582 case 1009: // toggle use of transform hint
4583 n = data.readInt32();
4584 mDebugDisableTransformHint = n ? 1 : 0;
4585 invalidateHwcGeometry();
4586 repaintEverything();
4587 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004588 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004589 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004590 reply->writeInt32(0);
4591 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004592 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004593 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004594 return NO_ERROR;
4595 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004596 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004597 if (!display) {
4598 return NAME_NOT_FOUND;
4599 }
4600
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004601 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004602 return NO_ERROR;
4603 }
4604 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004605 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004606 // daltonize
4607 n = data.readInt32();
4608 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004609 case 1:
4610 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4611 break;
4612 case 2:
4613 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4614 break;
4615 case 3:
4616 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4617 break;
4618 default:
4619 mDaltonizer.setType(ColorBlindnessType::None);
4620 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004621 }
4622 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004623 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004624 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004625 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004626 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004627
4628 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004629 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004630 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004631 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004632 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004633 // apply a color matrix
4634 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004635 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004636 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004637 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004638 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004639 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004640 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004641 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004642 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004643 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004644 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004645
4646 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4647 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004648 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004649 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4650 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4651 }
4652
Chia-I Wu28f320b2018-05-03 11:02:56 -07004653 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004654 return NO_ERROR;
4655 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004656 // This is an experimental interface
4657 // Needs to be shifted to proper binder interface when we productize
4658 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004659 n = data.readInt32();
4660 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004661 return NO_ERROR;
4662 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004663 case 1017: {
4664 n = data.readInt32();
4665 mForceFullDamage = static_cast<bool>(n);
4666 return NO_ERROR;
4667 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004668 case 1018: { // Modify Choreographer's phase offset
4669 n = data.readInt32();
4670 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4671 return NO_ERROR;
4672 }
4673 case 1019: { // Modify SurfaceFlinger's phase offset
4674 n = data.readInt32();
4675 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4676 return NO_ERROR;
4677 }
Irvel468051e2016-06-13 16:44:44 -07004678 case 1020: { // Layer updates interceptor
4679 n = data.readInt32();
4680 if (n) {
4681 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004682 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004683 }
4684 else{
4685 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004686 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004687 }
4688 return NO_ERROR;
4689 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004690 case 1021: { // Disable HWC virtual displays
4691 n = data.readInt32();
4692 mUseHwcVirtualDisplays = !n;
4693 return NO_ERROR;
4694 }
Romain Guy0147a172017-06-01 13:53:56 -07004695 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004696 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004697 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004698
Chia-I Wu28f320b2018-05-03 11:02:56 -07004699 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004700 return NO_ERROR;
4701 }
Romain Guy54f154a2017-10-24 21:40:32 +01004702 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004703 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004704 invalidateHwcGeometry();
4705 repaintEverything();
4706 return NO_ERROR;
4707 }
4708 case 1024: { // Is wide color gamut rendering/color management supported?
4709 reply->writeBool(hasWideColorDisplay);
4710 return NO_ERROR;
4711 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004712 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004713 n = data.readInt32();
4714 if (n) {
4715 ALOGV("LayerTracing enabled");
4716 mTracing.enable();
4717 doTracing("tracing.enable");
4718 reply->writeInt32(NO_ERROR);
4719 } else {
4720 ALOGV("LayerTracing disabled");
4721 status_t err = mTracing.disable();
4722 reply->writeInt32(err);
4723 }
4724 return NO_ERROR;
4725 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004726 case 1026: { // Get layer tracing status
4727 reply->writeBool(mTracing.isEnabled());
4728 return NO_ERROR;
4729 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004730 // Is a DisplayColorSetting supported?
4731 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004732 const auto display = getDefaultDisplayDevice();
4733 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004734 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004735 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004736
4737 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4738 switch (setting) {
4739 case DisplayColorSetting::MANAGED:
4740 reply->writeBool(hasWideColorDisplay);
4741 break;
4742 case DisplayColorSetting::UNMANAGED:
4743 reply->writeBool(true);
4744 break;
4745 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004746 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004747 break;
4748 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004749 reply->writeBool(
4750 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004751 break;
4752 }
4753 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004754 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004755 // Is VrFlinger active?
4756 case 1028: {
4757 Mutex::Autolock _l(mStateLock);
4758 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4759 return NO_ERROR;
4760 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004761 }
4762 }
4763 return err;
4764}
4765
Steven Thomas6d8110b2017-08-31 18:24:21 -07004766void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004767 android_atomic_or(1, &mRepaintEverything);
4768 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004769}
4770
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004771// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4772class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004773public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004774 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4775 ~WindowDisconnector() {
4776 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004777 }
4778
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004779private:
4780 ANativeWindow* mWindow;
4781 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004782};
4783
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004784status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4785 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4786 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4787 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004788 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004789 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004790
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004791 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004792
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004793 const auto display = getDisplayDeviceLocked(displayToken);
4794 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004795
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004796 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004797
4798 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004799 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004800 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004801}
4802
4803status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004804 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004805 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004806 ATRACE_CALL();
4807
4808 class LayerRenderArea : public RenderArea {
4809 public:
Robert Carr578038f2018-03-09 12:25:24 -08004810 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4811 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004812 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004813 mLayer(layer),
4814 mCrop(crop),
4815 mFlinger(flinger),
4816 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004817 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004818 Rect getBounds() const override {
4819 const Layer::State& layerState(mLayer->getDrawingState());
4820 return Rect(layerState.active.w, layerState.active.h);
4821 }
4822 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4823 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4824 bool isSecure() const override { return false; }
4825 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004826 Rect getSourceCrop() const override {
4827 if (mCrop.isEmpty()) {
4828 return getBounds();
4829 } else {
4830 return mCrop;
4831 }
4832 }
Robert Carr578038f2018-03-09 12:25:24 -08004833 class ReparentForDrawing {
4834 public:
4835 const sp<Layer>& oldParent;
4836 const sp<Layer>& newParent;
4837
4838 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4839 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004840 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004841 }
Robert Carr15eae092018-03-23 13:43:53 -07004842 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004843 };
4844
4845 void render(std::function<void()> drawLayers) override {
4846 if (!mChildrenOnly) {
4847 mTransform = mLayer->getTransform().inverse();
4848 drawLayers();
4849 } else {
4850 Rect bounds = getBounds();
4851 screenshotParentLayer =
4852 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4853 bounds.getWidth(), bounds.getHeight(), 0);
4854
4855 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4856 drawLayers();
4857 }
4858 }
chaviwa76b2712017-09-20 12:02:26 -07004859
chaviwa76b2712017-09-20 12:02:26 -07004860 private:
chaviw7206d492017-11-10 16:16:12 -08004861 const sp<Layer> mLayer;
4862 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004863
4864 // In the "childrenOnly" case we reparent the children to a screenshot
4865 // layer which has no properties set and which does not draw.
4866 sp<ContainerLayer> screenshotParentLayer;
4867 Transform mTransform;
4868
4869 SurfaceFlinger* mFlinger;
4870 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004871 };
4872
4873 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4874 auto parent = layerHandle->owner.promote();
4875
chaviw7206d492017-11-10 16:16:12 -08004876 if (parent == nullptr || parent->isPendingRemoval()) {
4877 ALOGE("captureLayers called with a removed parent");
4878 return NAME_NOT_FOUND;
4879 }
4880
Robert Carr578038f2018-03-09 12:25:24 -08004881 const int uid = IPCThreadState::self()->getCallingUid();
4882 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4883 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4884 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4885 return PERMISSION_DENIED;
4886 }
4887
chaviw7206d492017-11-10 16:16:12 -08004888 Rect crop(sourceCrop);
4889 if (sourceCrop.width() <= 0) {
4890 crop.left = 0;
4891 crop.right = parent->getCurrentState().active.w;
4892 }
4893
4894 if (sourceCrop.height() <= 0) {
4895 crop.top = 0;
4896 crop.bottom = parent->getCurrentState().active.h;
4897 }
4898
4899 int32_t reqWidth = crop.width() * frameScale;
4900 int32_t reqHeight = crop.height() * frameScale;
4901
Robert Carr578038f2018-03-09 12:25:24 -08004902 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004903
Robert Carr578038f2018-03-09 12:25:24 -08004904 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004905 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4906 if (!layer->isVisible()) {
4907 return;
Robert Carr578038f2018-03-09 12:25:24 -08004908 } else if (childrenOnly && layer == parent.get()) {
4909 return;
chaviwa76b2712017-09-20 12:02:26 -07004910 }
4911 visitor(layer);
4912 });
4913 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004914 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004915}
4916
4917status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4918 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004919 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004920 bool useIdentityTransform) {
4921 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004922
Iris Chang7501ed62018-04-30 14:45:42 +08004923 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004924
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004925 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4926 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4927 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4928 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004929
4930 // This mutex protects syncFd and captureResult for communication of the return values from the
4931 // main thread back to this Binder thread
4932 std::mutex captureMutex;
4933 std::condition_variable captureCondition;
4934 std::unique_lock<std::mutex> captureLock(captureMutex);
4935 int syncFd = -1;
4936 std::optional<status_t> captureResult;
4937
Robert Carr03480e22018-01-04 16:02:06 -08004938 const int uid = IPCThreadState::self()->getCallingUid();
4939 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4940
Dominik Laskowski8c001672018-05-30 16:52:06 -07004941 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004942 // If there is a refresh pending, bug out early and tell the binder thread to try again
4943 // after the refresh.
4944 if (mRefreshPending) {
4945 ATRACE_NAME("Skipping screenshot for now");
4946 std::unique_lock<std::mutex> captureLock(captureMutex);
4947 captureResult = std::make_optional<status_t>(EAGAIN);
4948 captureCondition.notify_one();
4949 return;
4950 }
4951
4952 status_t result = NO_ERROR;
4953 int fd = -1;
4954 {
4955 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07004956 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08004957 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4958 useIdentityTransform, forSystem, &fd);
4959 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004960 }
4961
4962 {
4963 std::unique_lock<std::mutex> captureLock(captureMutex);
4964 syncFd = fd;
4965 captureResult = std::make_optional<status_t>(result);
4966 captureCondition.notify_one();
4967 }
4968 });
4969
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004970 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004971 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004972 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004973 while (*captureResult == EAGAIN) {
4974 captureResult.reset();
4975 result = postMessageAsync(message);
4976 if (result != NO_ERROR) {
4977 return result;
4978 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07004979 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004980 }
4981 result = *captureResult;
4982 }
4983
4984 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004985 sync_wait(syncFd, -1);
4986 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004987 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004988
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004989 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004990}
4991
chaviwa76b2712017-09-20 12:02:26 -07004992void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4993 TraverseLayersFunction traverseLayers, bool yswap,
4994 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004995 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004996
Lloyd Pique144e1162017-12-20 16:44:52 -08004997 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004998
4999 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005000 const auto raWidth = renderArea.getWidth();
5001 const auto raHeight = renderArea.getHeight();
5002
5003 const auto reqWidth = renderArea.getReqWidth();
5004 const auto reqHeight = renderArea.getReqHeight();
5005 Rect sourceCrop = renderArea.getSourceCrop();
5006
Iris Chang7501ed62018-04-30 14:45:42 +08005007 bool filtering = false;
5008 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5009 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5010 static_cast<int32_t>(reqHeight) != raWidth;
5011 } else {
5012 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5013 static_cast<int32_t>(reqHeight) != raHeight;
5014 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005015
Dan Stozac1879002014-05-22 15:59:05 -07005016 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005017 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005018 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005019 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005020 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5021 Transform tr;
5022 uint32_t flags = 0x00;
5023 switch (mPrimaryDisplayOrientation) {
5024 case DisplayState::eOrientation90:
5025 flags = Transform::ROT_90;
5026 break;
5027 case DisplayState::eOrientation180:
5028 flags = Transform::ROT_180;
5029 break;
5030 case DisplayState::eOrientation270:
5031 flags = Transform::ROT_270;
5032 break;
5033 }
5034 tr.set(flags, raWidth, raHeight);
5035 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005036 }
5037
5038 // ensure that sourceCrop is inside screen
5039 if (sourceCrop.left < 0) {
5040 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5041 }
chaviwa76b2712017-09-20 12:02:26 -07005042 if (sourceCrop.right > raWidth) {
5043 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005044 }
5045 if (sourceCrop.top < 0) {
5046 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5047 }
chaviwa76b2712017-09-20 12:02:26 -07005048 if (sourceCrop.bottom > raHeight) {
5049 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005050 }
5051
Chia-I Wu36574d92018-05-16 10:54:36 -07005052 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5053 engine.setOutputDataSpace(Dataspace::SRGB);
5054 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005055
Mathias Agopian180f10d2013-04-10 22:55:41 -07005056 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005057 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005058
Iris Chang7501ed62018-04-30 14:45:42 +08005059 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5060 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5061 // convert hw orientation into flag presentation
5062 // here inverse transform needed
5063 uint8_t hw_rot_90 = 0x00;
5064 uint8_t hw_flip_hv = 0x00;
5065 switch (mPrimaryDisplayOrientation) {
5066 case DisplayState::eOrientation90:
5067 hw_rot_90 = Transform::ROT_90;
5068 hw_flip_hv = Transform::ROT_180;
5069 break;
5070 case DisplayState::eOrientation180:
5071 hw_flip_hv = Transform::ROT_180;
5072 break;
5073 case DisplayState::eOrientation270:
5074 hw_rot_90 = Transform::ROT_90;
5075 break;
5076 }
5077
5078 // transform flags operation
5079 // 1) flip H V if both have ROT_90 flag
5080 // 2) XOR these flags
5081 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5082 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5083 if (rotation_rot_90 & hw_rot_90) {
5084 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5085 }
5086 rotation = static_cast<Transform::orientation_flags>
5087 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5088 }
5089
Mathias Agopian180f10d2013-04-10 22:55:41 -07005090 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005091 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005092 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005093 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005094
chaviw50da5042018-04-09 13:49:37 -07005095 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005096 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005097 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005098
chaviwa76b2712017-09-20 12:02:26 -07005099 traverseLayers([&](Layer* layer) {
5100 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07005101 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005102 if (filtering) layer->setFiltering(false);
5103 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005104}
5105
chaviwa76b2712017-09-20 12:02:26 -07005106status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5107 TraverseLayersFunction traverseLayers,
5108 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005109 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005110 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005111 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005112 ATRACE_CALL();
5113
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005114 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005115
5116 traverseLayers([&](Layer* layer) {
5117 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5118 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005119
Robert Carr03480e22018-01-04 16:02:06 -08005120 // We allow the system server to take screenshots of secure layers for
5121 // use in situations like the Screen-rotation animation and place
5122 // the impetus on WindowManager to not persist them.
5123 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005124 ALOGW("FB is protected: PERMISSION_DENIED");
5125 return PERMISSION_DENIED;
5126 }
5127
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005128 // this binds the given EGLImage as a framebuffer for the
5129 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005130 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005131 if (bufferBond.getStatus() != NO_ERROR) {
5132 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005133 return INVALID_OPERATION;
5134 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005135
Dan Stozaabcda352017-06-01 14:37:39 -07005136 // this will in fact render into our dequeued buffer
5137 // via an FBO, which means we didn't have to create
5138 // an EGLSurface and therefore we're not
5139 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005140 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005141
Dan Stozaabcda352017-06-01 14:37:39 -07005142 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005143 getRenderEngine().finish();
5144 *outSyncFd = -1;
5145
chaviwa76b2712017-09-20 12:02:26 -07005146 const auto reqWidth = renderArea.getReqWidth();
5147 const auto reqHeight = renderArea.getReqHeight();
5148
Dan Stozaabcda352017-06-01 14:37:39 -07005149 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5150 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005151 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005152 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005153 } else {
5154 base::unique_fd syncFd = getRenderEngine().flush();
5155 if (syncFd < 0) {
5156 getRenderEngine().finish();
5157 }
5158 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005159 }
5160
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005161 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005162}
5163
Mathias Agopiand5556842013-09-19 17:08:37 -07005164void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005165 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005166 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005167 for (size_t y = 0; y < h; y++) {
5168 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5169 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005170 if (p[x] != 0xFF000000) return;
5171 }
5172 }
chaviwa76b2712017-09-20 12:02:26 -07005173 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005174
Robert Carr2047fae2016-11-28 14:09:09 -08005175 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005176 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005177 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005178 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5179 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5180 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5181 static_cast<float>(state.color.a));
5182 i++;
5183 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005184 }
5185}
5186
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005187// ---------------------------------------------------------------------------
5188
Dan Stoza412903f2017-04-27 13:42:17 -07005189void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5190 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005191}
5192
Dan Stoza412903f2017-04-27 13:42:17 -07005193void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5194 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005195}
5196
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005197void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5198 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005199 const LayerVector::Visitor& visitor) {
5200 // We loop through the first level of layers without traversing,
5201 // as we need to interpret min/max layer Z in the top level Z space.
5202 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005203 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005204 continue;
5205 }
5206 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005207 // relative layers are traversed in Layer::traverseInZOrder
5208 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005209 continue;
5210 }
5211 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005212 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005213 return;
5214 }
chaviwa76b2712017-09-20 12:02:26 -07005215 if (!layer->isVisible()) {
5216 return;
5217 }
5218 visitor(layer);
5219 });
5220 }
5221}
5222
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005223}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005224
Chia-I Wu30505fb2018-03-26 16:20:31 -07005225
Mathias Agopian3f844832013-08-07 21:24:32 -07005226#if defined(__gl_h_)
5227#error "don't include gl/gl.h in this file"
5228#endif
5229
5230#if defined(__gl2_h_)
5231#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005232#endif