blob: 9e0e82c8a46d41a26d51e389ddccce149d1f898e [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 Wu6d844112018-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"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include "Effects/Daltonizer.h"
87
Mathias Agopian875d8e12013-06-07 15:35:48 -070088#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070089#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070090
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080092#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
93#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090094#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090095
chaviw1d044282017-09-27 12:19:28 -070096#include <layerproto/LayerProtoParser.h>
97
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080098#define DISPLAY_COUNT 1
99
Mathias Agopianfee2b462013-07-03 12:34:01 -0700100/*
101 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
102 * black pixels.
103 */
104#define DEBUG_SCREENSHOTS false
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107
Jaesoo Lee43518572017-01-23 19:03:16 +0900108using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109using namespace android::hardware::configstore::V1_0;
Peiyong Linfd997e02018-03-28 15:29:00 -0700110using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700111using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700112using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700113using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
Steven Thomasb02664d2017-07-26 18:48:28 -0700115namespace {
116class ConditionalLock {
117public:
118 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
119 if (lock) {
120 mMutex.lock();
121 }
122 }
123 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
124private:
125 Mutex& mMutex;
126 bool mLocked;
127};
128} // namespace anonymous
129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130// ---------------------------------------------------------------------------
131
Mathias Agopian99b49842011-06-27 16:05:52 -0700132const String16 sHardwareTest("android.permission.HARDWARE_TEST");
133const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
134const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
135const String16 sDump("android.permission.DUMP");
136
137// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800138int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
139int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700140int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700141bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800142uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800143bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800144bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800145int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800146// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600147bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700148
Kalle Raitaa099a242017-01-11 11:17:29 -0800149
150std::string getHwcServiceName() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.hwc_service_name", value, "default");
153 ALOGI("Using HWComposer service: '%s'", value);
154 return std::string(value);
155}
156
157bool useTrebleTestingOverride() {
158 char value[PROPERTY_VALUE_MAX] = {};
159 property_get("debug.sf.treble_testing_override", value, "false");
160 ALOGI("Treble testing override: '%s'", value);
161 return std::string(value) == "true";
162}
163
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800164std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
165 switch(displayColorSetting) {
166 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700167 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800168 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700169 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800170 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700171 return std::string("Enhanced");
172 default:
173 return std::string("Unknown ") +
174 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800175 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800176}
177
Lloyd Pique09594832018-01-22 17:48:03 -0800178NativeWindowSurface::~NativeWindowSurface() = default;
179
180namespace impl {
181
182class NativeWindowSurface final : public android::NativeWindowSurface {
183public:
184 static std::unique_ptr<android::NativeWindowSurface> create(
185 const sp<IGraphicBufferProducer>& producer) {
186 return std::make_unique<NativeWindowSurface>(producer);
187 }
188
189 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
190 : surface(new Surface(producer, false)) {}
191
192 ~NativeWindowSurface() override = default;
193
194private:
195 sp<ANativeWindow> getNativeWindow() const override { return surface; }
196
197 void preallocateBuffers() override { surface->allocateBuffers(); }
198
199 sp<Surface> surface;
200};
201
202} // namespace impl
203
David Sodmanbc815282017-11-05 18:57:52 -0800204SurfaceFlingerBE::SurfaceFlingerBE()
205 : mHwcServiceName(getHwcServiceName()),
206 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800207 mFrameBuckets(),
208 mTotalTime(0),
209 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800210 mComposerSequenceId(0) {
211}
212
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800213SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800214 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800215 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700216 mTransactionPending(false),
217 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700218 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700219 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700220 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800221 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800222 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800224 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800225 mAnimCompositionPending(false),
Chia-I Wuad8d8272018-06-26 10:18:18 +0800226 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800227 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700228 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700229 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700230 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700231 mDebugInSwapBuffers(0),
232 mLastSwapBufferTime(0),
233 mDebugInTransaction(0),
234 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700235 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000236 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700237 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700238 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800239 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800240 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700241 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800242 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800243 mCreateBufferQueue(&BufferQueue::createBufferQueue),
244 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800245
246SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800247 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800248
249 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
250 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
251
252 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
253 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
254
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800255 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
256 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700258 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
259 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
260
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700261 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
262 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
263
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800264 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
265 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
266
Steven Thomas050b2c82017-03-06 11:45:16 -0800267 // Vr flinger is only enabled on Daydream ready devices.
268 useVrFlinger = getBool< ISurfaceFlingerConfigs,
269 &ISurfaceFlingerConfigs::useVrFlinger>(false);
270
Fabien Sanglard1971b632017-03-10 14:50:03 -0800271 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
272 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
273
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600274 hasWideColorDisplay =
275 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
276
Iris Chang7501ed62018-04-30 14:45:42 +0800277 V1_1::DisplayOrientation primaryDisplayOrientation =
278 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
279 V1_1::DisplayOrientation::ORIENTATION_0);
280
281 switch (primaryDisplayOrientation) {
282 case V1_1::DisplayOrientation::ORIENTATION_90:
283 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
284 break;
285 case V1_1::DisplayOrientation::ORIENTATION_180:
286 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
287 break;
288 case V1_1::DisplayOrientation::ORIENTATION_270:
289 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
290 break;
291 default:
292 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
293 break;
294 }
295 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
296
David Sodman99974d22017-11-28 12:04:33 -0800297 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700298
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299 // debugging stuff...
300 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700301
Mathias Agopianb4b17302013-03-20 18:36:41 -0700302 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700303 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700304
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 property_get("debug.sf.showupdates", value, "0");
306 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700307
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700308 property_get("debug.sf.ddms", value, "0");
309 mDebugDDMS = atoi(value);
310 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700311 if (!startDdmConnection()) {
312 // start failed, and DDMS debugging not enabled
313 mDebugDDMS = 0;
314 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700315 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700316 ALOGI_IF(mDebugRegion, "showupdates enabled");
317 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700318
319 property_get("debug.sf.disable_backpressure", value, "0");
320 mPropagateBackpressure = !atoi(value);
321 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700322
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800323 property_get("debug.sf.enable_hwc_vds", value, "0");
324 mUseHwcVirtualDisplays = atoi(value);
325 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800326
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800327 property_get("ro.sf.disable_triple_buffer", value, "1");
328 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800329 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700330
Yiwei Zhang243b3782018-05-15 17:40:04 -0700331 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700332 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
333 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
334
Jorim Jaggie203e042018-06-19 15:57:08 +0200335 property_get("debug.sf.early_phase_offset_ns", value, "-1");
336 const int earlySfOffsetNs = atoi(value);
337
338 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
339 const int earlyGlSfOffsetNs = atoi(value);
340
341 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
342 const int earlyAppOffsetNs = atoi(value);
343
344 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
345 const int earlyGlAppOffsetNs = atoi(value);
346
347 const VSyncModulator::Offsets earlyOffsets =
348 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
349 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
350 const VSyncModulator::Offsets earlyGlOffsets =
351 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
352 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
353 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
354 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza2713c302018-03-28 17:07:36 -0700355
Romain Guy11d63f42017-07-20 12:47:14 -0700356 // We should be reading 'persist.sys.sf.color_saturation' here
357 // but since /data may be encrypted, we need to wait until after vold
358 // comes online to attempt to read the property. The property is
359 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800360
361 if (useTrebleTestingOverride()) {
362 // Without the override SurfaceFlinger cannot connect to HIDL
363 // services that are not listed in the manifests. Considered
364 // deriving the setting from the set service name, but it
365 // would be brittle if the name that's not 'default' is used
366 // for production purposes later on.
367 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
368 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800369}
370
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800371void SurfaceFlinger::onFirstRef()
372{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800373 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800374}
375
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376SurfaceFlinger::~SurfaceFlinger()
377{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378}
379
Dan Stozac7014012014-02-14 15:03:43 -0800380void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800381{
382 // the window manager died on us. prepare its eulogy.
383
Andy McFadden13a082e2012-08-24 10:16:42 -0700384 // restore initial conditions (default device unblank, etc)
385 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800386
387 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700388 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800389}
390
Robert Carr1db73f62016-12-21 12:58:51 -0800391static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700392 status_t err = client->initCheck();
393 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800394 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800395 }
Robert Carr1db73f62016-12-21 12:58:51 -0800396 return nullptr;
397}
398
399sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
400 return initClient(new Client(this));
401}
402
403sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
404 const sp<IGraphicBufferProducer>& gbp) {
405 if (authenticateSurfaceTexture(gbp) == false) {
406 return nullptr;
407 }
408 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
409 if (layer == nullptr) {
410 return nullptr;
411 }
412
413 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414}
415
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700416sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
417 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700418{
419 class DisplayToken : public BBinder {
420 sp<SurfaceFlinger> flinger;
421 virtual ~DisplayToken() {
422 // no more references, this display must be terminated
423 Mutex::Autolock _l(flinger->mStateLock);
424 flinger->mCurrentState.displays.removeItem(this);
425 flinger->setTransactionFlags(eDisplayTransactionNeeded);
426 }
427 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700428 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700429 : flinger(flinger) {
430 }
431 };
432
433 sp<BBinder> token = new DisplayToken(this);
434
435 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700436 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700437 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800439 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440 return token;
441}
442
Jesse Hall6c913be2013-08-08 12:15:49 -0700443void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
444 Mutex::Autolock _l(mStateLock);
445
446 ssize_t idx = mCurrentState.displays.indexOfKey(display);
447 if (idx < 0) {
448 ALOGW("destroyDisplay: invalid display token");
449 return;
450 }
451
452 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
453 if (!info.isVirtualDisplay()) {
454 ALOGE("destroyDisplay called for non-virtual display");
455 return;
456 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800457 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700458 mCurrentState.displays.removeItemsAt(idx);
459 setTransactionFlags(eDisplayTransactionNeeded);
460}
461
Mathias Agopiane57f2922012-08-09 16:29:12 -0700462sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700463 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800465 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700466 }
Jesse Hall692c7232012-11-08 15:41:56 -0800467 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700468}
469
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800470void SurfaceFlinger::bootFinished()
471{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700472 if (mStartPropertySetThread->join() != NO_ERROR) {
473 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800474 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800475 const nsecs_t now = systemTime();
476 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000477 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700478
479 // wait patiently for the window manager death
480 const String16 name("window");
481 sp<IBinder> window(defaultServiceManager()->getService(name));
482 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700483 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700484 }
485
Steven Thomas050b2c82017-03-06 11:45:16 -0800486 if (mVrFlinger) {
487 mVrFlinger->OnBootFinished();
488 }
489
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700490 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700491 // formerly we would just kill the process, but we now ask it to exit so it
492 // can choose where to stop the animation.
493 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700494
495 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
496 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
497 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700498
Thierry Strudel2924d012017-08-14 15:19:37 -0700499 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700500 readPersistentProperties();
Chia-I Wuad8d8272018-06-26 10:18:18 +0800501 mBootStage = BootStage::FINISHED;
Romain Guy11d63f42017-07-20 12:47:14 -0700502 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700503 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800504}
505
Dan Stoza9fdb7e02018-06-21 12:10:12 -0700506uint32_t SurfaceFlinger::getNewTexture() {
507 {
508 std::lock_guard lock(mTexturePoolMutex);
509 if (!mTexturePool.empty()) {
510 uint32_t name = mTexturePool.back();
511 mTexturePool.pop_back();
512 ATRACE_INT("TexturePoolSize", mTexturePool.size());
513 return name;
514 }
515
516 // The pool was too small, so increase it for the future
517 ++mTexturePoolSize;
518 }
519
520 // The pool was empty, so we need to get a new texture name directly using a
521 // blocking call to the main thread
522 uint32_t name = 0;
523 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
524 return name;
525}
526
Mathias Agopian3f844832013-08-07 21:24:32 -0700527void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700528 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800529 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700530 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700531 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800532 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
533 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700534 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700535 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700536 return true;
537 }
538 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700539 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700540}
541
Lloyd Piquee83f9312018-02-01 12:53:17 -0800542class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700543public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700544 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000545 const char* name) :
546 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700547 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700548 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000549 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
550 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700551 mDispSync(dispSync),
552 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700553 mVsyncMutex(),
554 mPhaseOffset(phaseOffset),
555 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700556
Lloyd Piquee83f9312018-02-01 12:53:17 -0800557 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700558
Lloyd Piquee83f9312018-02-01 12:53:17 -0800559 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700560 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700561 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000562 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700563 static_cast<DispSync::Callback*>(this));
564 if (err != NO_ERROR) {
565 ALOGE("error registering vsync callback: %s (%d)",
566 strerror(-err), err);
567 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700568 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700569 } else {
570 status_t err = mDispSync->removeEventListener(
571 static_cast<DispSync::Callback*>(this));
572 if (err != NO_ERROR) {
573 ALOGE("error unregistering vsync callback: %s (%d)",
574 strerror(-err), err);
575 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700576 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700578 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700579 }
580
Lloyd Piquee83f9312018-02-01 12:53:17 -0800581 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700582 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700583 mCallback = callback;
584 }
585
Lloyd Piquee83f9312018-02-01 12:53:17 -0800586 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700587 Mutex::Autolock lock(mVsyncMutex);
588
589 // Normalize phaseOffset to [0, period)
590 auto period = mDispSync->getPeriod();
591 phaseOffset %= period;
592 if (phaseOffset < 0) {
593 // If we're here, then phaseOffset is in (-period, 0). After this
594 // operation, it will be in (0, period)
595 phaseOffset += period;
596 }
597 mPhaseOffset = phaseOffset;
598
599 // If we're not enabled, we don't need to mess with the listeners
600 if (!mEnabled) {
601 return;
602 }
603
Dan Stoza2713c302018-03-28 17:07:36 -0700604 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
605 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700606 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700607 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700608 strerror(-err), err);
609 }
610 }
611
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700612private:
613 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800614 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700615 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700616 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700617 callback = mCallback;
618
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700619 if (mTraceVsync) {
620 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700621 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700622 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700623 }
624
Peiyong Lin566a3b42018-01-09 18:22:43 -0800625 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700626 callback->onVSyncEvent(when);
627 }
628 }
629
Tim Murray4a4e4a22016-04-19 16:29:23 +0000630 const char* const mName;
631
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700632 int mValue;
633
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700634 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700635 const String8 mVsyncOnLabel;
636 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700637
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700638 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700639
640 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800641 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700642
643 Mutex mVsyncMutex; // Protects the following
644 nsecs_t mPhaseOffset;
645 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700646};
647
Lloyd Piquee83f9312018-02-01 12:53:17 -0800648class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700649public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800650 InjectVSyncSource() = default;
651 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700652
Lloyd Piquee83f9312018-02-01 12:53:17 -0800653 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700654 std::lock_guard<std::mutex> lock(mCallbackMutex);
655 mCallback = callback;
656 }
657
Lloyd Piquee83f9312018-02-01 12:53:17 -0800658 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700659 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700660 if (mCallback) {
661 mCallback->onVSyncEvent(when);
662 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700663 }
664
Lloyd Piquee83f9312018-02-01 12:53:17 -0800665 void setVSyncEnabled(bool) override {}
666 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700667
668private:
669 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800670 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700671};
672
Wei Wangf9b05ee2017-07-19 20:59:39 -0700673// Do not call property_set on main thread which will be blocked by init
674// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700675void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700676 ALOGI( "SurfaceFlinger's main thread ready to run. "
677 "Initializing graphics H/W...");
678
Thierry Strudel2924d012017-08-14 15:19:37 -0700679 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900680
Steven Thomasb02664d2017-07-26 18:48:28 -0700681 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800682
Steven Thomasb02664d2017-07-26 18:48:28 -0700683 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800684 mEventThreadSource =
685 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
686 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800687 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
688 [this]() { resyncWithRateLimit(); },
689 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800690 "appEventThread");
691 mSfEventThreadSource =
692 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
693 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800694
Lloyd Pique24b0a482018-03-09 18:52:26 -0800695 mSFEventThread =
696 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
697 [this]() { resyncWithRateLimit(); },
698 [this](nsecs_t timestamp) {
699 mInterceptor->saveVSyncEvent(timestamp);
700 },
701 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800702 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggie203e042018-06-19 15:57:08 +0200703 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800704
Steven Thomasb02664d2017-07-26 18:48:28 -0700705 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800706 getBE().mRenderEngine =
707 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
708 hasWideColorDisplay
709 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
710 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800711 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700712
713 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
714 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800715 getBE().mHwc.reset(
716 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700717 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800718 // Process any initial hotplug and resulting display changes.
719 processDisplayHotplugEventsLocked();
720 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
721 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800722
Lloyd Piquefcd86612017-12-14 17:15:36 -0800723 // make the default display GLContext current so that we can create textures
724 // when creating Layers (which may happens before we render something)
725 getDefaultDisplayDeviceLocked()->makeCurrent();
726
Steven Thomas050b2c82017-03-06 11:45:16 -0800727 if (useVrFlinger) {
728 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700729 // This callback is called from the vr flinger dispatch thread. We
730 // need to call signalTransaction(), which requires holding
731 // mStateLock when we're not on the main thread. Acquiring
732 // mStateLock from the vr flinger dispatch thread might trigger a
733 // deadlock in surface flinger (see b/66916578), so post a message
734 // to be handled on the main thread instead.
735 sp<LambdaMessage> message = new LambdaMessage([=]() {
736 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
737 mVrFlingerRequestsDisplay = requestDisplay;
738 signalTransaction();
739 });
740 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800741 };
David Sodman105b7dc2017-11-04 20:28:14 -0700742 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
743 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800744 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800745 if (!mVrFlinger) {
746 ALOGE("Failed to start vrflinger");
747 }
748 }
749
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800750 mEventControlThread = std::make_unique<impl::EventControlThread>(
751 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700752
Mathias Agopian92a979a2012-08-02 18:32:23 -0700753 // initialize our drawing state
754 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700755
Andy McFadden13a082e2012-08-24 10:16:42 -0700756 // set initial conditions (e.g. unblank default device)
757 initializeDisplays();
758
David Sodmanbc815282017-11-05 18:57:52 -0800759 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700760
Wei Wangf9b05ee2017-07-19 20:59:39 -0700761 // Inform native graphics APIs whether the present timestamp is supported:
762 if (getHwComposer().hasCapability(
763 HWC2::Capability::PresentFenceIsNotReliable)) {
764 mStartPropertySetThread = new StartPropertySetThread(false);
765 } else {
766 mStartPropertySetThread = new StartPropertySetThread(true);
767 }
768
769 if (mStartPropertySetThread->Start() != NO_ERROR) {
770 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800771 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800772
Chia-I Wu6d844112018-06-27 07:17:41 +0800773 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
774 // is used to saturate legacy sRGB content. However, to make sure the same color under
775 // Display P3 will be saturated to the same color, we intentionally break the API spec
776 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
777 // such saturation matrix on Display P3 is understood fully, the API should always return
778 // identify matrix.
779 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800780 Dataspace::SRGB_LINEAR);
781
Chia-I Wu6d844112018-06-27 07:17:41 +0800782 // we will apply this on Display P3.
783 if (mEnhancedSaturationMatrix != mat4()) {
784 ColorSpace srgb(ColorSpace::sRGB());
785 ColorSpace displayP3(ColorSpace::DisplayP3());
786 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
787 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
788 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
789 }
790
Dan Stoza9e56aa02015-11-02 13:00:03 -0800791 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700792}
793
Romain Guy11d63f42017-07-20 12:47:14 -0700794void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700795 Mutex::Autolock _l(mStateLock);
796
Romain Guy11d63f42017-07-20 12:47:14 -0700797 char value[PROPERTY_VALUE_MAX];
798
799 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800800 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700801 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800802 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100803
804 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700805 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700806}
807
Mathias Agopiana67e4182012-06-19 17:26:12 -0700808void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800809 // Start boot animation service by setting a property mailbox
810 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700811 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800812 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700813 if (mStartPropertySetThread->join() != NO_ERROR) {
814 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800815 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700816}
817
Mathias Agopian875d8e12013-06-07 15:35:48 -0700818size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800819 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700820}
821
Mathias Agopian875d8e12013-06-07 15:35:48 -0700822size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800823 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700824}
825
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800826// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800827
Jamie Gennis582270d2011-08-17 18:19:00 -0700828bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800829 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800830 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800831 return authenticateSurfaceTextureLocked(bufferProducer);
832}
833
834bool SurfaceFlinger::authenticateSurfaceTextureLocked(
835 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800836 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800837 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800838}
839
Brian Anderson6b376712017-04-04 10:51:39 -0700840status_t SurfaceFlinger::getSupportedFrameTimestamps(
841 std::vector<FrameEvent>* outSupported) const {
842 *outSupported = {
843 FrameEvent::REQUESTED_PRESENT,
844 FrameEvent::ACQUIRE,
845 FrameEvent::LATCH,
846 FrameEvent::FIRST_REFRESH_START,
847 FrameEvent::LAST_REFRESH_START,
848 FrameEvent::GPU_COMPOSITION_DONE,
849 FrameEvent::DEQUEUE_READY,
850 FrameEvent::RELEASE,
851 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700852 ConditionalLock _l(mStateLock,
853 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700854 if (!getHwComposer().hasCapability(
855 HWC2::Capability::PresentFenceIsNotReliable)) {
856 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
857 }
858 return NO_ERROR;
859}
860
Dan Stoza7f7da322014-05-02 15:26:25 -0700861status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
862 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800863 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 return BAD_VALUE;
865 }
866
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500867 if (!display.get())
868 return NAME_NOT_FOUND;
869
Jesse Hall692c7232012-11-08 15:41:56 -0800870 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700871 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800872 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700873 type = i;
874 break;
875 }
876 }
877
878 if (type < 0) {
879 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700880 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700881
Mathias Agopian8b736f12012-08-13 17:54:26 -0700882 // TODO: Not sure if display density should handled by SF any longer
883 class Density {
884 static int getDensityFromProperty(char const* propName) {
885 char property[PROPERTY_VALUE_MAX];
886 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800887 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700888 density = atoi(property);
889 }
890 return density;
891 }
892 public:
893 static int getEmuDensity() {
894 return getDensityFromProperty("qemu.sf.lcd_density"); }
895 static int getBuildDensity() {
896 return getDensityFromProperty("ro.sf.lcd_density"); }
897 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700898
Dan Stoza7f7da322014-05-02 15:26:25 -0700899 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700900
Steven Thomas6d8110b2017-08-31 18:24:21 -0700901 ConditionalLock _l(mStateLock,
902 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800903 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700904 DisplayInfo info = DisplayInfo();
905
Dan Stoza9e56aa02015-11-02 13:00:03 -0800906 float xdpi = hwConfig->getDpiX();
907 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700908
909 if (type == DisplayDevice::DISPLAY_PRIMARY) {
910 // The density of the device is provided by a build property
911 float density = Density::getBuildDensity() / 160.0f;
912 if (density == 0) {
913 // the build doesn't provide a density -- this is wrong!
914 // use xdpi instead
915 ALOGE("ro.sf.lcd_density must be defined as a build property");
916 density = xdpi / 160.0f;
917 }
918 if (Density::getEmuDensity()) {
919 // if "qemu.sf.lcd_density" is specified, it overrides everything
920 xdpi = ydpi = density = Density::getEmuDensity();
921 density /= 160.0f;
922 }
923 info.density = density;
924
925 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700926 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800927 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700928 } else {
929 // TODO: where should this value come from?
930 static const int TV_DENSITY = 213;
931 info.density = TV_DENSITY / 160.0f;
932 info.orientation = 0;
933 }
934
Dan Stoza9e56aa02015-11-02 13:00:03 -0800935 info.w = hwConfig->getWidth();
936 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700937 info.xdpi = xdpi;
938 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800939 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900940 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800941
Andy McFadden91b2ca82014-06-13 14:04:23 -0700942 // This is how far in advance a buffer must be queued for
943 // presentation at a given time. If you want a buffer to appear
944 // on the screen at time N, you must submit the buffer before
945 // (N - presentationDeadline).
946 //
947 // Normally it's one full refresh period (to give SF a chance to
948 // latch the buffer), but this can be reduced by configuring a
949 // DispSync offset. Any additional delays introduced by the hardware
950 // composer or panel must be accounted for here.
951 //
952 // We add an additional 1ms to allow for processing time and
953 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800954 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800955 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700956
957 // All non-virtual displays are currently considered secure.
958 info.secure = true;
959
Iris Chang7501ed62018-04-30 14:45:42 +0800960 if (type == DisplayDevice::DISPLAY_PRIMARY &&
961 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
962 std::swap(info.w, info.h);
963 }
964
Michael Wright28f24d02016-07-12 13:30:53 -0700965 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700966 }
967
Dan Stoza7f7da322014-05-02 15:26:25 -0700968 return NO_ERROR;
969}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700970
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800971status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700972 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800973 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700974 return BAD_VALUE;
975 }
976
977 // FIXME for now we always return stats for the primary display
978 memset(stats, 0, sizeof(*stats));
979 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
980 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
981 return NO_ERROR;
982}
983
Yiwei Zhang1d465af2018-08-21 15:15:42 -0700984status_t SurfaceFlinger::getDisplayViewport(const sp<IBinder>& display, Rect* outViewport) {
985 if (outViewport == nullptr || display.get() == nullptr) {
986 return BAD_VALUE;
987 }
988
989 sp<const DisplayDevice> device(getDisplayDevice(display));
990 if (device == nullptr) {
991 return BAD_VALUE;
992 }
993
994 *outViewport = device->getViewport();
995
996 return NO_ERROR;
997}
998
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700999int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08001000 if (display == nullptr) {
1001 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +08001002 return BAD_VALUE;
1003 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001004
1005 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -08001006 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -07001007 return device->getActiveConfig();
1008 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001009
Dan Stoza24a42e92015-03-09 10:04:11 -07001010 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -07001011}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001012
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001013void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
1014 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
1015 this);
1016 int32_t type = hw->getDisplayType();
1017 int currentMode = hw->getActiveConfig();
1018
1019 if (mode == currentMode) {
1020 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
1021 return;
1022 }
1023
1024 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1025 ALOGW("Trying to set config for virtual display");
1026 return;
1027 }
1028
1029 hw->setActiveConfig(mode);
1030 getHwComposer().setActiveConfig(type, mode);
1031}
1032
1033status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
1034 class MessageSetActiveConfig: public MessageBase {
1035 SurfaceFlinger& mFlinger;
1036 sp<IBinder> mDisplay;
1037 int mMode;
1038 public:
1039 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1040 int mode) :
1041 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1042 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -07001043 Vector<DisplayInfo> configs;
1044 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -07001045 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -07001046 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -07001047 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -07001048 return true;
Michael Lentine7306c672014-07-30 13:00:37 -07001049 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001050 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08001051 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001052 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07001053 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001054 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
1055 ALOGW("Attempt to set active config = %d for virtual display",
1056 mMode);
1057 } else {
1058 mFlinger.setActiveConfigInternal(hw, mMode);
1059 }
1060 return true;
1061 }
1062 };
1063 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
1064 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -07001065 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001066}
Michael Wright28f24d02016-07-12 13:30:53 -07001067status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001068 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001069 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
1070 return BAD_VALUE;
1071 }
1072
1073 if (!display.get()) {
1074 return NAME_NOT_FOUND;
1075 }
1076
1077 int32_t type = NAME_NOT_FOUND;
1078 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
1079 if (display == mBuiltinDisplays[i]) {
1080 type = i;
1081 break;
1082 }
1083 }
1084
1085 if (type < 0) {
1086 return type;
1087 }
1088
Peiyong Lina52f0292018-03-14 17:26:31 -07001089 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001090 {
1091 ConditionalLock _l(mStateLock,
1092 std::this_thread::get_id() != mMainThreadId);
1093 modes = getHwComposer().getColorModes(type);
1094 }
Michael Wright28f24d02016-07-12 13:30:53 -07001095 outColorModes->clear();
1096 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1097
1098 return NO_ERROR;
1099}
1100
Peiyong Lina52f0292018-03-14 17:26:31 -07001101ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001102 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001103 if (device != nullptr) {
1104 return device->getActiveColorMode();
1105 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001106 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001107}
1108
1109void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001110 ColorMode mode, Dataspace dataSpace,
1111 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001112 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001113 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001114 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001115 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001116
Peiyong Lin38e9a562018-04-10 16:24:20 -07001117 if (mode == currentMode && dataSpace == currentDataSpace &&
1118 renderIntent == currentRenderIntent) {
1119 return;
1120 }
1121
1122 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1123 ALOGW("Trying to set config for virtual display");
1124 return;
1125 }
1126
1127 hw->setActiveColorMode(mode);
1128 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001129 hw->setActiveRenderIntent(renderIntent);
1130 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1131
1132 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1133 decodeColorMode(mode).c_str(), mode,
1134 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1135 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001136}
1137
1138
1139status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001140 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001141 class MessageSetActiveColorMode: public MessageBase {
1142 SurfaceFlinger& mFlinger;
1143 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001144 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001145 public:
1146 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001147 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001148 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1149 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001150 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001151 mFlinger.getDisplayColorModes(mDisplay, &modes);
1152 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001153 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001154 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1155 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001156 return true;
1157 }
1158 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1159 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001160 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1161 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001162 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001163 ALOGW("Attempt to set active color mode %s %d for virtual display",
1164 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001165 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001166 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1167 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001168 }
1169 return true;
1170 }
1171 };
1172 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1173 postMessageSync(msg);
1174 return NO_ERROR;
1175}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001176
Svetoslavd85084b2014-03-20 10:28:31 -07001177status_t SurfaceFlinger::clearAnimationFrameStats() {
1178 Mutex::Autolock _l(mStateLock);
1179 mAnimFrameTracker.clearStats();
1180 return NO_ERROR;
1181}
1182
1183status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1184 Mutex::Autolock _l(mStateLock);
1185 mAnimFrameTracker.getStats(outStats);
1186 return NO_ERROR;
1187}
1188
Dan Stozac4f471e2016-03-24 09:31:08 -07001189status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1190 HdrCapabilities* outCapabilities) const {
1191 Mutex::Autolock _l(mStateLock);
1192
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001193 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001194 if (displayDevice == nullptr) {
1195 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1196 return BAD_VALUE;
1197 }
1198
Peiyong Linfb069302018-04-25 14:34:31 -07001199 // At this point the DisplayDeivce should already be set up,
1200 // meaning the luminance information is already queried from
1201 // hardware composer and stored properly.
1202 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1203 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1204 capabilities.getDesiredMaxLuminance(),
1205 capabilities.getDesiredMaxAverageLuminance(),
1206 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001207
1208 return NO_ERROR;
1209}
1210
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001211status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001212 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1213 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001214
Chia-I Wu90f669f2017-10-05 14:24:41 -07001215 if (mInjectVSyncs == enable) {
1216 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001217 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001218
1219 if (enable) {
1220 ALOGV("VSync Injections enabled");
1221 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001222 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001223 mInjectorEventThread = std::make_unique<
1224 impl::EventThread>(mVSyncInjector.get(),
1225 [this]() { resyncWithRateLimit(); },
1226 impl::EventThread::InterceptVSyncsCallback(),
1227 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001228 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001229 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001230 } else {
1231 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001232 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001233 }
1234
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001235 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001236 });
1237 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001238 return NO_ERROR;
1239}
1240
1241status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001242 Mutex::Autolock _l(mStateLock);
1243
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001244 if (!mInjectVSyncs) {
1245 ALOGE("VSync Injections not enabled");
1246 return BAD_VALUE;
1247 }
1248 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1249 ALOGV("Injecting VSync inside SurfaceFlinger");
1250 mVSyncInjector->onInjectSyncEvent(when);
1251 }
1252 return NO_ERROR;
1253}
1254
Vishnu Nair927b3b12020-06-22 11:52:39 -07001255status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers)
Lloyd Pique755e3192018-01-31 16:46:15 -08001256 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001257 IPCThreadState* ipc = IPCThreadState::self();
1258 const int pid = ipc->getCallingPid();
1259 const int uid = ipc->getCallingUid();
1260 if ((uid != AID_SHELL) &&
1261 !PermissionCache::checkPermission(sDump, pid, uid)) {
1262 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1263 return PERMISSION_DENIED;
1264 }
1265
Kalle Raitaa099a242017-01-11 11:17:29 -08001266 outLayers->clear();
Vishnu Nair927b3b12020-06-22 11:52:39 -07001267 postMessageSync(new LambdaMessage([&]() {
1268 mDrawingState.traverseInZOrder([&](Layer* layer) {
1269 outLayers->push_back(layer->getLayerDebugInfo());
1270 });
Kalle Raitaa099a242017-01-11 11:17:29 -08001271
Vishnu Nair927b3b12020-06-22 11:52:39 -07001272 }));
Kalle Raitaa099a242017-01-11 11:17:29 -08001273 return NO_ERROR;
1274}
1275
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001276// ----------------------------------------------------------------------------
1277
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001278sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1279 ISurfaceComposer::VsyncSource vsyncSource) {
1280 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1281 return mSFEventThread->createEventConnection();
1282 } else {
1283 return mEventThread->createEventConnection();
1284 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001285}
1286
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001287// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001288
1289void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001290 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001291}
1292
1293void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001294 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001295}
1296
1297void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001298 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001299}
1300
1301void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001302 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001303 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001304}
1305
1306status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001307 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001308 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001309}
1310
1311status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001312 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001313 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001314 if (res == NO_ERROR) {
1315 msg->wait();
1316 }
1317 return res;
1318}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001319
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001320void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001321 do {
1322 waitForEvent();
1323 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001324}
1325
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001326void SurfaceFlinger::enableHardwareVsync() {
1327 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001328 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001329 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001330 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1331 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001332 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001333 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001334}
1335
Jesse Hall948fe0c2013-10-14 12:56:09 -07001336void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001337 Mutex::Autolock _l(mHWVsyncLock);
1338
Jesse Hall948fe0c2013-10-14 12:56:09 -07001339 if (makeAvailable) {
1340 mHWVsyncAvailable = true;
1341 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001342 // Hardware vsync is not currently available, so abort the resync
1343 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001344 return;
1345 }
1346
David Sodman105b7dc2017-11-04 20:28:14 -07001347 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001348 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001349
1350 mPrimaryDispSync.reset();
1351 mPrimaryDispSync.setPeriod(period);
1352
1353 if (!mPrimaryHWVsyncEnabled) {
1354 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001355 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1356 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001357 mPrimaryHWVsyncEnabled = true;
1358 }
1359}
1360
Jesse Hall948fe0c2013-10-14 12:56:09 -07001361void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001362 Mutex::Autolock _l(mHWVsyncLock);
1363 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001364 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1365 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001366 mPrimaryDispSync.endResync();
1367 mPrimaryHWVsyncEnabled = false;
1368 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001369 if (makeUnavailable) {
1370 mHWVsyncAvailable = false;
1371 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001372}
1373
Tim Murray4a4e4a22016-04-19 16:29:23 +00001374void SurfaceFlinger::resyncWithRateLimit() {
1375 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001376
1377 // No explicit locking is needed here since EventThread holds a lock while calling this method
1378 static nsecs_t sLastResyncAttempted = 0;
1379 const nsecs_t now = systemTime();
1380 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001381 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001382 }
Dan Stoza57164302017-05-08 14:03:54 -07001383 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001384}
1385
Steven Thomasb02664d2017-07-26 18:48:28 -07001386void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1387 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001388 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001389 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001390 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001391 return;
1392 }
1393
1394 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001395 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001396 return;
1397 }
1398
Jamie Gennisd1700752013-10-14 12:22:52 -07001399 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001400
Jamie Gennisd1700752013-10-14 12:22:52 -07001401 { // Scope for the lock
1402 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001403 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001404 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001405 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001406 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001407
1408 if (needsHwVsync) {
1409 enableHardwareVsync();
1410 } else {
1411 disableHardwareVsync(false);
1412 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001413}
1414
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001415void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001416 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1417 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001418}
1419
Lloyd Pique715a2c12017-12-14 17:18:08 -08001420void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1421 HWC2::Connection connection) {
1422 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1423 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001424
Lloyd Piqueba04e622017-12-14 17:11:26 -08001425 // Ignore events that do not have the right sequenceId.
1426 if (sequenceId != getBE().mComposerSequenceId) {
1427 return;
1428 }
1429
Steven Thomasb02664d2017-07-26 18:48:28 -07001430 // Only lock if we're not on the main thread. This function is normally
1431 // called on a hwbinder thread, but for the primary display it's called on
1432 // the main thread with the state lock already held, so don't attempt to
1433 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001434 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001435
Lloyd Pique715a2c12017-12-14 17:18:08 -08001436 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001437
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001438 if (std::this_thread::get_id() == mMainThreadId) {
1439 // Process all pending hot plug events immediately if we are on the main thread.
1440 processDisplayHotplugEventsLocked();
1441 }
1442
Lloyd Piqueba04e622017-12-14 17:11:26 -08001443 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001444}
1445
Steven Thomasb02664d2017-07-26 18:48:28 -07001446void SurfaceFlinger::onRefreshReceived(int sequenceId,
1447 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001448 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001449 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001450 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001451 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001452 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001453}
1454
Dan Stoza9e56aa02015-11-02 13:00:03 -08001455void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001456 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001458 getHwComposer().setVsyncEnabled(disp,
1459 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001460}
1461
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001462// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001463void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001464 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001465 // Clear the drawing state so that the logic inside of
1466 // handleTransactionLocked will fire. It will determine the delta between
1467 // mCurrentState and mDrawingState and re-apply all changes when we make the
1468 // transition.
1469 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001470 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001471 mDisplays.clear();
1472}
1473
Steven Thomas050b2c82017-03-06 11:45:16 -08001474void SurfaceFlinger::updateVrFlinger() {
1475 if (!mVrFlinger)
1476 return;
1477 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001478 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001479 return;
1480 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001481
David Sodman105b7dc2017-11-04 20:28:14 -07001482 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001483 ALOGE("Vr flinger is only supported for remote hardware composer"
1484 " service connections. Ignoring request to transition to vr"
1485 " flinger.");
1486 mVrFlingerRequestsDisplay = false;
1487 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001488 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001489
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001490 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001491
Steven Thomasb02664d2017-07-26 18:48:28 -07001492 int currentDisplayPowerMode = getDisplayDeviceLocked(
1493 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001494
Steven Thomasb02664d2017-07-26 18:48:28 -07001495 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001496 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001497 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001498
Steven Thomasb02664d2017-07-26 18:48:28 -07001499 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001500 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001501 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1502 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001503 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001504
David Sodman105b7dc2017-11-04 20:28:14 -07001505 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1506 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001507
1508 if (vrFlingerRequestsDisplay) {
1509 mVrFlinger->GrantDisplayOwnership();
1510 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001511 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001512 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001513
1514 mVisibleRegionsDirty = true;
1515 invalidateHwcGeometry();
1516
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001517 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001518 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1519 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1520 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001521
Steven Thomasb02664d2017-07-26 18:48:28 -07001522 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001523 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001524 const nsecs_t period = activeConfig->getVsyncPeriod();
1525 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001526
Steven Thomasb02664d2017-07-26 18:48:28 -07001527 // Use phase of 0 since phase is not known.
1528 // Use latency of 0, which will snap to the ideal latency.
1529 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001530
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001531 android_atomic_or(1, &mRepaintEverything);
1532 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001533}
1534
Mathias Agopian4fec8732012-06-29 14:12:52 -07001535void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001536 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001537 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001538 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001539 bool frameMissed = !mHadClientComposition &&
1540 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001541 (mPreviousPresentFence->getSignalTime() ==
1542 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001543 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001544 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001545 mTimeStats.incrementMissedFrames();
1546 if (mPropagateBackpressure) {
1547 signalLayerUpdate();
1548 break;
1549 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001550 }
Dan Stoza50182882016-07-08 12:02:20 -07001551
Steven Thomas050b2c82017-03-06 11:45:16 -08001552 // Now that we're going to make it to the handleMessageTransaction()
1553 // call below it's safe to call updateVrFlinger(), which will
1554 // potentially trigger a display handoff.
1555 updateVrFlinger();
1556
Dan Stoza6b9454d2014-11-07 16:00:59 -08001557 bool refreshNeeded = handleMessageTransaction();
1558 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001559 refreshNeeded |= mRepaintEverything;
Chia-I Wuad8d8272018-06-26 10:18:18 +08001560 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001561 // Signal a refresh if a transaction modified the window state,
1562 // a new buffer was latched, or if HWC has requested a full
1563 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001564 signalRefresh();
1565 }
1566 break;
1567 }
1568 case MessageQueue::REFRESH: {
1569 handleMessageRefresh();
1570 break;
1571 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001572 }
1573}
1574
Dan Stoza6b9454d2014-11-07 16:00:59 -08001575bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001576 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001577 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001578 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001579 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001580 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001581 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001582}
1583
Dan Stoza6b9454d2014-11-07 16:00:59 -08001584bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001585 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001586 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001587}
1588
1589void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001590 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001591
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001592 mRefreshPending = false;
1593
Pablo Ceballos40845df2016-01-25 17:41:15 -08001594 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001595
Brian Andersond6927fb2016-07-23 23:37:30 -07001596 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001597 rebuildLayerStacks();
1598 setUpHWComposer();
1599 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001600 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001601 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001602 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001603 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001604
David Sodman105b7dc2017-11-04 20:28:14 -07001605 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001606
1607 mHadClientComposition = false;
1608 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1609 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1610 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001611 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001612 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001613 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001614
Dan Stoza9e56aa02015-11-02 13:00:03 -08001615 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001616}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001617
Mathias Agopiancd60f992012-08-16 16:28:27 -07001618void SurfaceFlinger::doDebugFlashRegions()
1619{
1620 // is debugging enabled
1621 if (CC_LIKELY(!mDebugRegion))
1622 return;
1623
1624 const bool repaintEverything = mRepaintEverything;
1625 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1626 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001627 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001628 // transform the dirty region into this screen's coordinate space
1629 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1630 if (!dirtyRegion.isEmpty()) {
1631 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001632 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001633
1634 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001635 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001636 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001637 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1638
Mathias Agopianda27af92012-09-13 18:17:13 -07001639 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001640 }
1641 }
1642 }
1643
1644 postFramebuffer();
1645
1646 if (mDebugRegion > 1) {
1647 usleep(mDebugRegion * 1000);
1648 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001649
Dan Stoza9e56aa02015-11-02 13:00:03 -08001650 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001651 auto& displayDevice = mDisplays[displayId];
1652 if (!displayDevice->isDisplayOn()) {
1653 continue;
1654 }
1655
David Sodman105b7dc2017-11-04 20:28:14 -07001656 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1657 ALOGE_IF(result != NO_ERROR,
1658 "prepareFrame for display %zd failed:"
1659 " %d (%s)",
1660 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001661 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001662}
1663
Adrian Roos1e1a1282017-11-01 19:05:31 +01001664void SurfaceFlinger::doTracing(const char* where) {
1665 ATRACE_CALL();
1666 ATRACE_NAME(where);
1667 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001668 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001669 }
1670}
1671
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001672void SurfaceFlinger::logLayerStats() {
1673 ATRACE_CALL();
1674 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1675 int32_t hwcId = -1;
1676 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1677 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1678 if (displayDevice->isPrimary()) {
1679 hwcId = displayDevice->getHwcDisplayId();
1680 break;
1681 }
1682 }
1683 if (hwcId < 0) {
1684 ALOGE("LayerStats: Hmmm, no primary display?");
1685 return;
1686 }
1687 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1688 }
1689}
1690
Brian Andersond6927fb2016-07-23 23:37:30 -07001691void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001692{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001693 ATRACE_CALL();
1694 ALOGV("preComposition");
1695
Mathias Agopiancd60f992012-08-16 16:28:27 -07001696 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001697 mDrawingState.traverseInZOrder([&](Layer* layer) {
1698 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699 needExtraInvalidate = true;
1700 }
Robert Carr2047fae2016-11-28 14:09:09 -08001701 });
1702
Mathias Agopiancd60f992012-08-16 16:28:27 -07001703 if (needExtraInvalidate) {
1704 signalLayerUpdate();
1705 }
1706}
1707
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001708void SurfaceFlinger::updateCompositorTiming(
1709 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1710 std::shared_ptr<FenceTime>& presentFenceTime) {
1711 // Update queue of past composite+present times and determine the
1712 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001713 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001714 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001715 while (!getBE().mCompositePresentTimes.empty()) {
1716 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001717 // Cached values should have been updated before calling this method,
1718 // which helps avoid duplicate syscalls.
1719 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1720 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1721 break;
1722 }
1723 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001724 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001725 }
1726
1727 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001728 while (getBE().mCompositePresentTimes.size() > 16) {
1729 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001730 }
1731
Brian Andersond0010582017-03-07 13:20:31 -08001732 setCompositorTimingSnapped(
1733 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1734}
1735
1736void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1737 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001738 // Integer division and modulo round toward 0 not -inf, so we need to
1739 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001740 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001741 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1742 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1743
Brian Andersond0010582017-03-07 13:20:31 -08001744 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1745 if (idealLatency <= 0) {
1746 idealLatency = vsyncInterval;
1747 }
1748
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001749 // Snap the latency to a value that removes scheduling jitter from the
1750 // composition and present times, which often have >1ms of jitter.
1751 // Reducing jitter is important if an app attempts to extrapolate
1752 // something (such as user input) to an accurate diasplay time.
1753 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1754 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001755 nsecs_t bias = vsyncInterval / 2;
1756 int64_t extraVsyncs =
1757 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1758 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1759 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001760
David Sodman99974d22017-11-28 12:04:33 -08001761 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1762 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1763 getBE().mCompositorTiming.interval = vsyncInterval;
1764 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001765}
1766
1767void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001768{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001769 ATRACE_CALL();
1770 ALOGV("postComposition");
1771
Brian Anderson3546a3f2016-07-14 11:51:14 -07001772 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001773 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001774 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001775 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001776 }
1777
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001778 // |mStateLock| not needed as we are on the main thread
1779 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001780
David Sodman73beded2017-11-15 11:56:06 -08001781 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001782 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001783 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001784 glCompositionDoneFenceTime =
1785 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001786 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001787 } else {
1788 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1789 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001790
David Sodman73beded2017-11-15 11:56:06 -08001791 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001792 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001793 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001794 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001795
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001796 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1797 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1798
1799 // We use the refreshStartTime which might be sampled a little later than
1800 // when we started doing work for this frame, but that should be okay
1801 // since updateCompositorTiming has snapping logic.
1802 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001803 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001804 CompositorTiming compositorTiming;
1805 {
David Sodman99974d22017-11-28 12:04:33 -08001806 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1807 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001808 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001809
Robert Carr2047fae2016-11-28 14:09:09 -08001810 mDrawingState.traverseInZOrder([&](Layer* layer) {
1811 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001812 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001813 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001814 recordBufferingStats(layer->getName().string(),
1815 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001816 }
Robert Carr2047fae2016-11-28 14:09:09 -08001817 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001818
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001819 if (presentFenceTime->isValid()) {
1820 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001821 enableHardwareVsync();
1822 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001823 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001824 }
1825 }
1826
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001827 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001828 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001829 enableHardwareVsync();
1830 }
1831 }
1832
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001833 if (mAnimCompositionPending) {
1834 mAnimCompositionPending = false;
1835
Brian Anderson4e606e32017-03-16 15:34:57 -07001836 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001837 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001838 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001839 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001840 // The HWC doesn't support present fences, so use the refresh
1841 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001842 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001843 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001844 mAnimFrameTracker.setActualPresentTime(presentTime);
1845 }
1846 mAnimFrameTracker.advanceFrame();
1847 }
Dan Stozab90cf072015-03-05 11:05:59 -08001848
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001849 mTimeStats.incrementTotalFrames();
1850 if (mHadClientComposition) {
1851 mTimeStats.incrementClientCompositionFrames();
1852 }
1853
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001854 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1855 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001856 return;
1857 }
1858
1859 nsecs_t currentTime = systemTime();
1860 if (mHasPoweredOff) {
1861 mHasPoweredOff = false;
1862 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001863 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001864 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001865 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1866 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001867 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001868 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001869 }
David Sodman4a36e932017-11-07 14:29:47 -08001870 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001871 }
David Sodman4a36e932017-11-07 14:29:47 -08001872 getBE().mLastSwapTime = currentTime;
Dan Stoza9fdb7e02018-06-21 12:10:12 -07001873
1874 {
1875 std::lock_guard lock(mTexturePoolMutex);
1876 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1877 if (refillCount > 0) {
1878 const size_t offset = mTexturePool.size();
1879 mTexturePool.resize(mTexturePoolSize);
1880 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1881 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1882 }
1883 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001884}
1885
1886void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001887 ATRACE_CALL();
1888 ALOGV("rebuildLayerStacks");
1889
Mathias Agopiancd60f992012-08-16 16:28:27 -07001890 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001891 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001892 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001893 mVisibleRegionsDirty = false;
1894 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001895
Jeff Sharkey76488112017-02-27 14:15:18 -07001896 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1897 Region opaqueRegion;
1898 Region dirtyRegion;
1899 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001900 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001901 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1902 const Transform& tr(displayDevice->getTransform());
1903 const Rect bounds(displayDevice->getBounds());
1904 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001905 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001906
Jeff Sharkey76488112017-02-27 14:15:18 -07001907 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001908 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001909 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1910 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001911 Region drawRegion(tr.transform(
1912 layer->visibleNonTransparentRegion));
1913 drawRegion.andSelf(bounds);
1914 if (!drawRegion.isEmpty()) {
1915 layersSortedByZ.add(layer);
1916 } else {
1917 // Clear out the HWC layer if this layer was
1918 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001919 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001920 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001921 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001922 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001923 // WM changes displayDevice->layerStack upon sleep/awake.
1924 // Here we make sure we delete the HWC layers even if
1925 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001926 hwcLayerDestroyed = layer->destroyHwcLayer(
1927 displayDevice->getHwcDisplayId());
1928 }
1929
1930 // If a layer is not going to get a release fence because
1931 // it is invisible, but it is also going to release its
1932 // old buffer, add it to the list of layers needing
1933 // fences.
1934 if (hwcLayerDestroyed) {
1935 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1936 mLayersWithQueuedFrames.cend(), layer);
1937 if (found != mLayersWithQueuedFrames.cend()) {
1938 layersNeedingFences.add(layer);
1939 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001940 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001941 });
1942 }
1943 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001944 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001945 displayDevice->undefinedRegion.set(bounds);
1946 displayDevice->undefinedRegion.subtractSelf(
1947 tr.transform(opaqueRegion));
1948 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001949 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001950 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001951}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001952
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001953// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001954// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001955// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001956// - Dataspace::DISPLAY_P3
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001957// The returned HDR data space is one of
1958// - Dataspace::UNKNOWN
1959// - Dataspace::BT2020_HLG
1960// - Dataspace::BT2020_PQ
1961Dataspace SurfaceFlinger::getBestDataspace(
1962 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1963 Dataspace bestDataSpace = Dataspace::SRGB;
1964 *outHdrDataSpace = Dataspace::UNKNOWN;
1965
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001966 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07001967 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001968 case Dataspace::V0_SCRGB:
1969 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001970 case Dataspace::DISPLAY_P3:
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001971 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001972 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001973 case Dataspace::BT2020_PQ:
1974 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001975 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001976 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001977 case Dataspace::BT2020_HLG:
1978 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001979 // When there's mixed PQ content and HLG content, we set the HDR
1980 // data space to be BT2020_PQ and convert HLG to PQ.
1981 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1982 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001983 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001984 break;
1985 default:
1986 break;
1987 }
Romain Guy54f154a2017-10-24 21:40:32 +01001988 }
1989
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001990 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001991}
1992
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001993// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001994void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001995 ColorMode* outMode, Dataspace* outDataSpace,
1996 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001997 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1998 *outMode = ColorMode::NATIVE;
1999 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002000 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002001 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002002 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002003
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002004 Dataspace hdrDataSpace;
2005 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
2006
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07002007 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002008 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07002009 !displayDevice->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002010 if (isHdr) {
2011 bestDataSpace = hdrDataSpace;
2012 }
2013
Chia-I Wu0d711262018-05-21 15:19:35 -07002014 RenderIntent intent;
2015 switch (mDisplayColorSetting) {
2016 case DisplayColorSetting::MANAGED:
2017 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002018 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002019 break;
2020 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002021 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002022 break;
2023 default: // vendor display color setting
2024 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2025 break;
2026 }
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002027
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002028 displayDevice->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002029}
2030
Mathias Agopiancd60f992012-08-16 16:28:27 -07002031void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002032 ATRACE_CALL();
2033 ALOGV("setUpHWComposer");
2034
Jesse Hall028dc8f2013-08-20 16:35:32 -07002035 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07002036 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07002037 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2038 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2039
2040 // If nothing has changed (!dirty), don't recompose.
2041 // If something changed, but we don't currently have any visible layers,
2042 // and didn't when we last did a composition, then skip it this time.
2043 // The second rule does two things:
2044 // - When all layers are removed from a display, we'll emit one black
2045 // frame, then nothing more until we get new layers.
2046 // - When a display is created with a private layer stack, we won't
2047 // emit any black frames until a layer is added to the layer stack.
2048 bool mustRecompose = dirty && !(empty && wasEmpty);
2049
2050 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2051 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2052 mustRecompose ? "doing" : "skipping",
2053 dirty ? "+" : "-",
2054 empty ? "+" : "-",
2055 wasEmpty ? "+" : "-");
2056
Dan Stoza71433162014-02-04 16:22:36 -08002057 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002058
2059 if (mustRecompose) {
2060 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2061 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002062 }
2063
Dan Stoza9e56aa02015-11-02 13:00:03 -08002064 // build the h/w work list
2065 if (CC_UNLIKELY(mGeometryInvalid)) {
2066 mGeometryInvalid = false;
2067 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2068 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2069 const auto hwcId = displayDevice->getHwcDisplayId();
2070 if (hwcId >= 0) {
2071 const Vector<sp<Layer>>& currentLayers(
2072 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002073 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002074 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002075 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002076 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002077 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002078 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002079 }
2080 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002081
Robert Carrae060832016-11-28 10:51:00 -08002082 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002083 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002084 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002085 }
2086 }
2087 }
2088 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002089 }
Riley Andrews03414a12014-07-01 14:22:59 -07002090
Dan Stoza9e56aa02015-11-02 13:00:03 -08002091 // Set the per-frame data
2092 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2093 auto& displayDevice = mDisplays[displayId];
2094 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002095
Dan Stoza9e56aa02015-11-02 13:00:03 -08002096 if (hwcId < 0) {
2097 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002098 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002099 if (mDrawingState.colorMatrixChanged) {
2100 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2101 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002102 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2103 "display %zd: %d", displayId, result);
2104 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002105 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu07376a92018-06-05 15:46:58 -07002106 if (layer->isHdrY410()) {
2107 layer->forceClientComposition(hwcId);
2108 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2109 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002110 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002111 layer->forceClientComposition(hwcId);
Chia-I Wu07376a92018-06-05 15:46:58 -07002112 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2113 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002114 !displayDevice->hasHLGSupport()) {
2115 layer->forceClientComposition(hwcId);
2116 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002117
chaviwc9232ed2017-11-14 15:31:15 -08002118 if (layer->getForceClientComposition(hwcId)) {
2119 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2120 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2121 continue;
2122 }
2123
Dan Stoza9e56aa02015-11-02 13:00:03 -08002124 layer->setPerFrameData(displayDevice);
2125 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002126
2127 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002128 ColorMode colorMode;
2129 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002130 RenderIntent renderIntent;
2131 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2132 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002133 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002134 }
2135
Chia-I Wu28f320b2018-05-03 11:02:56 -07002136 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002137
Dan Stoza9e56aa02015-11-02 13:00:03 -08002138 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002139 auto& displayDevice = mDisplays[displayId];
2140 if (!displayDevice->isDisplayOn()) {
2141 continue;
2142 }
2143
David Sodman105b7dc2017-11-04 20:28:14 -07002144 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002145 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2146 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002147 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002148}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002149
Mathias Agopiancd60f992012-08-16 16:28:27 -07002150void SurfaceFlinger::doComposition() {
2151 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002152 ALOGV("doComposition");
2153
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002154 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002155 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002156 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002157 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002158 // transform the dirty region into this screen's coordinate space
2159 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002160
2161 // repaint the framebuffer (if needed)
2162 doDisplayComposition(hw, dirtyRegion);
2163
Mathias Agopiancd60f992012-08-16 16:28:27 -07002164 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002165 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002166 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002167 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002168 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002169}
2170
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002171void SurfaceFlinger::postFramebuffer()
2172{
Mathias Agopian841cde52012-03-01 15:44:37 -08002173 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002174 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002175
Mathias Agopiana44b0412011-10-16 18:46:35 -07002176 const nsecs_t now = systemTime();
2177 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002178
Dan Stoza9e56aa02015-11-02 13:00:03 -08002179 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2180 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002181 if (!displayDevice->isDisplayOn()) {
2182 continue;
2183 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002184 const auto hwcId = displayDevice->getHwcDisplayId();
2185 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002186 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002187 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002188 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002189 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002190 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu99b46192018-06-21 15:52:50 +08002191 sp<Fence> releaseFence = Fence::NO_FENCE;
2192
Chia-I Wu7b549592017-11-15 09:14:57 -08002193 // The layer buffer from the previous frame (if any) is released
2194 // by HWC only when the release fence from this frame (if any) is
2195 // signaled. Always get the release fence from HWC first.
2196 auto hwcLayer = layer->getHwcLayer(hwcId);
Chia-I Wu99b46192018-06-21 15:52:50 +08002197 if (hwcId >= 0) {
2198 releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
2199 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002200
2201 // If the layer was client composited in the previous frame, we
2202 // need to merge with the previous client target acquire fence.
2203 // Since we do not track that, always merge with the current
2204 // client target acquire fence when it is available, even though
2205 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002206 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002207 releaseFence = Fence::merge("LayerRelease", releaseFence,
2208 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002209 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002210
Dan Stoza9e56aa02015-11-02 13:00:03 -08002211 layer->onLayerDisplayed(releaseFence);
2212 }
Chia-I Wu83806892017-11-16 10:50:20 -08002213
2214 // We've got a list of layers needing fences, that are disjoint with
2215 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2216 // supply them with the present fence.
2217 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002218 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002219 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2220 layer->onLayerDisplayed(presentFence);
2221 }
2222 }
2223
Dan Stoza9e56aa02015-11-02 13:00:03 -08002224 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002225 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002226 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002227 }
2228
Mathias Agopiana44b0412011-10-16 18:46:35 -07002229 mLastSwapBufferTime = systemTime() - now;
2230 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002231
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002232 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002233 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2234 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2235 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2236 logFrameStats();
2237 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002238 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002239}
2240
Mathias Agopian87baae12012-07-31 12:38:26 -07002241void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002242{
Mathias Agopian841cde52012-03-01 15:44:37 -08002243 ATRACE_CALL();
2244
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002245 // here we keep a copy of the drawing state (that is the state that's
2246 // going to be overwritten by handleTransactionLocked()) outside of
2247 // mStateLock so that the side-effects of the State assignment
2248 // don't happen with mStateLock held (which can cause deadlocks).
2249 State drawingState(mDrawingState);
2250
Mathias Agopianca4d3602011-05-19 15:38:14 -07002251 Mutex::Autolock _l(mStateLock);
2252 const nsecs_t now = systemTime();
2253 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002254
Mathias Agopianca4d3602011-05-19 15:38:14 -07002255 // Here we're guaranteed that some transaction flags are set
2256 // so we can call handleTransactionLocked() unconditionally.
2257 // We call getTransactionFlags(), which will also clear the flags,
2258 // with mStateLock held to guarantee that mCurrentState won't change
2259 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002260
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002261 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002262 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002263 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002264
Mathias Agopianca4d3602011-05-19 15:38:14 -07002265 mLastTransactionTime = systemTime() - now;
2266 mDebugInTransaction = 0;
2267 invalidateHwcGeometry();
2268 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002269}
2270
Lloyd Pique715a2c12017-12-14 17:18:08 -08002271DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002272 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002273 // Figure out whether the event is for the primary display or an
2274 // external display by matching the Hwc display id against one for a
2275 // connected display. If we did not find a match, we then check what
2276 // displays are not already connected to determine the type. If we don't
2277 // have a connected primary display, we assume the new display is meant to
2278 // be the primary display, and then if we don't have an external display,
2279 // we assume it is that.
2280 const auto primaryDisplayId =
2281 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2282 const auto externalDisplayId =
2283 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2284 if (primaryDisplayId && primaryDisplayId == display) {
2285 return DisplayDevice::DISPLAY_PRIMARY;
2286 } else if (externalDisplayId && externalDisplayId == display) {
2287 return DisplayDevice::DISPLAY_EXTERNAL;
2288 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2289 return DisplayDevice::DISPLAY_PRIMARY;
2290 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2291 return DisplayDevice::DISPLAY_EXTERNAL;
2292 }
2293
2294 return DisplayDevice::DISPLAY_ID_INVALID;
2295}
2296
Lloyd Piqueba04e622017-12-14 17:11:26 -08002297void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2298 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002299 auto displayType = determineDisplayType(event.display, event.connection);
2300 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2301 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2302 continue;
2303 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002304
2305 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2306 ALOGE("External displays are not supported by the vr hardware composer.");
2307 continue;
2308 }
2309
Lloyd Pique715a2c12017-12-14 17:18:08 -08002310 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002311
2312 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002313 if (!mBuiltinDisplays[displayType].get()) {
2314 ALOGV("Creating built in display %d", displayType);
2315 mBuiltinDisplays[displayType] = new BBinder();
2316 // All non-virtual displays are currently considered secure.
2317 DisplayDeviceState info(displayType, true);
2318 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2319 "Built-in Screen" : "External Screen";
2320 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002321 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002322 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002323 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002324 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002325
Lloyd Piquefcd86612017-12-14 17:15:36 -08002326 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2327 if (idx >= 0) {
2328 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002329 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002330 mCurrentState.displays.removeItemsAt(idx);
2331 }
2332 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002333 }
2334
2335 processDisplayChangesLocked();
2336 }
2337
2338 mPendingHotplugEvents.clear();
2339}
2340
Lloyd Pique09594832018-01-22 17:48:03 -08002341sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2342 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2343 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002344 bool hasWideColorGamut = false;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002345 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu99b46192018-06-21 15:52:50 +08002346 HdrCapabilities hdrCapabilities;
2347 int32_t supportedPerFrameMetadata = 0;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002348
Chia-I Wu99b46192018-06-21 15:52:50 +08002349 if (hasWideColorDisplay && hwcId >= 0) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002350 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002351 for (ColorMode colorMode : modes) {
2352 switch (colorMode) {
2353 case ColorMode::DISPLAY_P3:
2354 case ColorMode::ADOBE_RGB:
2355 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002356 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002357 break;
2358 default:
2359 break;
2360 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002361
2362 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2363 colorMode);
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002364 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique09594832018-01-22 17:48:03 -08002365 }
2366 }
2367
Chia-I Wu99b46192018-06-21 15:52:50 +08002368 if (hwcId >= 0) {
2369 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
2370 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(hwcId);
2371 }
Lloyd Pique09594832018-01-22 17:48:03 -08002372
2373 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2374 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2375
2376 /*
2377 * Create our display's surface
2378 */
2379 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2380 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2381 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2382 renderSurface->setNativeWindow(nativeWindow.get());
2383 const int displayWidth = renderSurface->queryWidth();
2384 const int displayHeight = renderSurface->queryHeight();
2385
2386 // Make sure that composition can never be stalled by a virtual display
2387 // consumer that isn't processing buffers fast enough. We have to do this
2388 // in two places:
2389 // * Here, in case the display is composed entirely by HWC.
2390 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2391 // window's swap interval in eglMakeCurrent, so they'll override the
2392 // interval we set here.
2393 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2394 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2395 }
2396
2397 // virtual displays are always considered enabled
2398 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2399 : HWC_POWER_MODE_OFF;
2400
2401 sp<DisplayDevice> hw =
2402 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2403 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002404 hasWideColorGamut, hdrCapabilities,
Chia-I Wu99b46192018-06-21 15:52:50 +08002405 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002406
2407 if (maxFrameBufferAcquiredBuffers >= 3) {
2408 nativeWindowSurface->preallocateBuffers();
2409 }
2410
2411 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002412 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2413 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002414 defaultColorMode = ColorMode::SRGB;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002415 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002416 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002417 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2418 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002419 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2420 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2421 }
Lloyd Pique09594832018-01-22 17:48:03 -08002422 hw->setLayerStack(state.layerStack);
2423 hw->setProjection(state.orientation, state.viewport, state.frame);
2424 hw->setDisplayName(state.displayName);
2425
2426 return hw;
2427}
2428
Lloyd Pique347200f2017-12-14 17:00:15 -08002429void SurfaceFlinger::processDisplayChangesLocked() {
2430 // here we take advantage of Vector's copy-on-write semantics to
2431 // improve performance by skipping the transaction entirely when
2432 // know that the lists are identical
2433 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2434 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2435 if (!curr.isIdenticalTo(draw)) {
2436 mVisibleRegionsDirty = true;
2437 const size_t cc = curr.size();
2438 size_t dc = draw.size();
2439
2440 // find the displays that were removed
2441 // (ie: in drawing state but not in current state)
2442 // also handle displays that changed
2443 // (ie: displays that are in both lists)
2444 for (size_t i = 0; i < dc;) {
2445 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2446 if (j < 0) {
2447 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002448 // Call makeCurrent() on the primary display so we can
2449 // be sure that nothing associated with this display
2450 // is current.
2451 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2452 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2453 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2454 if (hw != nullptr) hw->disconnect(getHwComposer());
2455 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2456 mEventThread->onHotplugReceived(draw[i].type, false);
2457 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002458 } else {
2459 // this display is in both lists. see if something changed.
2460 const DisplayDeviceState& state(curr[j]);
2461 const wp<IBinder>& display(curr.keyAt(j));
2462 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2463 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2464 if (state_binder != draw_binder) {
2465 // changing the surface is like destroying and
2466 // recreating the DisplayDevice, so we just remove it
2467 // from the drawing state, so that it get re-added
2468 // below.
2469 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2470 if (hw != nullptr) hw->disconnect(getHwComposer());
2471 mDisplays.removeItem(display);
2472 mDrawingState.displays.removeItemsAt(i);
2473 dc--;
2474 // at this point we must loop to the next item
2475 continue;
2476 }
2477
2478 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2479 if (disp != nullptr) {
2480 if (state.layerStack != draw[i].layerStack) {
2481 disp->setLayerStack(state.layerStack);
2482 }
2483 if ((state.orientation != draw[i].orientation) ||
2484 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2485 disp->setProjection(state.orientation, state.viewport, state.frame);
2486 }
2487 if (state.width != draw[i].width || state.height != draw[i].height) {
2488 disp->setDisplaySize(state.width, state.height);
2489 }
2490 }
2491 }
2492 ++i;
2493 }
2494
2495 // find displays that were added
2496 // (ie: in current state but not in drawing state)
2497 for (size_t i = 0; i < cc; i++) {
2498 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2499 const DisplayDeviceState& state(curr[i]);
2500
2501 sp<DisplaySurface> dispSurface;
2502 sp<IGraphicBufferProducer> producer;
2503 sp<IGraphicBufferProducer> bqProducer;
2504 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002505 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002506
2507 int32_t hwcId = -1;
2508 if (state.isVirtualDisplay()) {
2509 // Virtual displays without a surface are dormant:
2510 // they have external state (layer stack, projection,
2511 // etc.) but no internal state (i.e. a DisplayDevice).
2512 if (state.surface != nullptr) {
2513 // Allow VR composer to use virtual displays.
2514 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2515 int width = 0;
2516 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2517 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2518 int height = 0;
2519 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2520 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2521 int intFormat = 0;
2522 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2523 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002524 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002525
2526 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2527 }
2528
2529 // TODO: Plumb requested format back up to consumer
2530
2531 sp<VirtualDisplaySurface> vds =
2532 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2533 bqProducer, bqConsumer,
2534 state.displayName);
2535
2536 dispSurface = vds;
2537 producer = vds;
2538 }
2539 } else {
2540 ALOGE_IF(state.surface != nullptr,
2541 "adding a supported display, but rendering "
2542 "surface is provided (%p), ignoring it",
2543 state.surface.get());
2544
2545 hwcId = state.type;
2546 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2547 producer = bqProducer;
2548 }
2549
2550 const wp<IBinder>& display(curr.keyAt(i));
2551 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002552 mDisplays.add(display,
2553 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2554 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002555 if (!state.isVirtualDisplay()) {
2556 mEventThread->onHotplugReceived(state.type, true);
2557 }
2558 }
2559 }
2560 }
2561 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002562
2563 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002564}
2565
Mathias Agopian87baae12012-07-31 12:38:26 -07002566void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002567{
Dan Stoza7dde5992015-05-22 09:51:44 -07002568 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002569 mCurrentState.traverseInZOrder([](Layer* layer) {
2570 layer->notifyAvailableFrames();
2571 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002572
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573 /*
2574 * Traversal of the children
2575 * (perform the transaction for each of them if needed)
2576 */
2577
Mathias Agopian3559b072012-08-15 13:46:03 -07002578 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002579 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002581 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582
2583 const uint32_t flags = layer->doTransaction(0);
2584 if (flags & Layer::eVisibleRegion)
2585 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002586 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 }
2588
2589 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002590 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591 */
2592
Mathias Agopiane57f2922012-08-09 16:29:12 -07002593 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002594 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002595 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002596 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002598 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002599 // The transform hint might have changed for some layers
2600 // (either because a display has changed, or because a layer
2601 // as changed).
2602 //
2603 // Walk through all the layers in currentLayers,
2604 // and update their transform hint.
2605 //
2606 // If a layer is visible only on a single display, then that
2607 // display is used to calculate the hint, otherwise we use the
2608 // default display.
2609 //
2610 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2611 // the hint is set before we acquire a buffer from the surface texture.
2612 //
2613 // NOTE: layer transactions have taken place already, so we use their
2614 // drawing state. However, SurfaceFlinger's own transaction has not
2615 // happened yet, so we must use the current state layer list
2616 // (soon to become the drawing state list).
2617 //
2618 sp<const DisplayDevice> disp;
2619 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002620 bool first = true;
2621 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002622 // NOTE: we rely on the fact that layers are sorted by
2623 // layerStack first (so we don't have to traverse the list
2624 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002625 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002626 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002627 currentlayerStack = layerStack;
2628 // figure out if this layerstack is mirrored
2629 // (more than one display) if so, pick the default display,
2630 // if not, pick the only display it's on.
2631 disp.clear();
2632 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2633 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002634 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002635 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002636 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002637 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002638 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002639 break;
2640 }
2641 }
2642 }
2643 }
Chet Haase91d25932013-04-11 15:24:55 -07002644
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002645 if (disp == nullptr) {
2646 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2647 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002648
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002649 // could be null when this layer is using a layerStack
2650 // that is not visible on any display. Also can occur at
2651 // screen off/on times.
2652 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002653 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002654
2655 // disp can be null if there is no display available at all to get
2656 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002657 if (disp != nullptr) {
2658 layer->updateTransformHint(disp);
2659 }
Robert Carr2047fae2016-11-28 14:09:09 -08002660
2661 first = false;
2662 });
Mathias Agopian84300952012-11-21 16:02:13 -08002663 }
2664
2665
Mathias Agopian3559b072012-08-15 13:46:03 -07002666 /*
2667 * Perform our own transaction if needed
2668 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002669
2670 if (mLayersAdded) {
2671 mLayersAdded = false;
2672 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002673 mVisibleRegionsDirty = true;
2674 }
2675
2676 // some layers might have been removed, so
2677 // we need to update the regions they're exposing.
2678 if (mLayersRemoved) {
2679 mLayersRemoved = false;
2680 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002681 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002682 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002683 // this layer is not visible anymore
2684 // TODO: we could traverse the tree from front to back and
2685 // compute the actual visible region
2686 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002687 Region visibleReg;
2688 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002689 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002690 }
Robert Carr2047fae2016-11-28 14:09:09 -08002691 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002692 }
2693
2694 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002695
2696 updateCursorAsync();
2697}
2698
2699void SurfaceFlinger::updateCursorAsync()
2700{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002701 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2702 auto& displayDevice = mDisplays[displayId];
2703 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002704 continue;
2705 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002706
2707 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2708 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002709 }
2710 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002711}
2712
2713void SurfaceFlinger::commitTransaction()
2714{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002715 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002716 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002717 for (const auto& l : mLayersPendingRemoval) {
2718 recordBufferingStats(l->getName().string(),
2719 l->getOccupancyHistory(true));
2720 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002721 }
2722 mLayersPendingRemoval.clear();
2723 }
2724
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002725 // If this transaction is part of a window animation then the next frame
2726 // we composite should be considered an animation as well.
2727 mAnimCompositionPending = mAnimTransactionPending;
2728
Mathias Agopian4fec8732012-06-29 14:12:52 -07002729 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002730 // clear the "changed" flags in current state
2731 mCurrentState.colorMatrixChanged = false;
2732
Robert Carr1f0a16a2016-10-24 16:27:39 -07002733 mDrawingState.traverseInZOrder([](Layer* layer) {
2734 layer->commitChildList();
2735 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002736 mTransactionPending = false;
2737 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002738 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739}
2740
Chia-I Wuab0c3192017-08-01 11:29:00 -07002741void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002742 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743{
Mathias Agopian841cde52012-03-01 15:44:37 -08002744 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002745 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002746
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747 Region aboveOpaqueLayers;
2748 Region aboveCoveredLayers;
2749 Region dirty;
2750
Mathias Agopian87baae12012-07-31 12:38:26 -07002751 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752
Robert Carr2047fae2016-11-28 14:09:09 -08002753 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002754 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002755 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756
Jesse Hall01e29052013-02-19 16:13:35 -08002757 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002758 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002759 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002760
Mathias Agopianab028732010-03-16 16:41:46 -07002761 /*
2762 * opaqueRegion: area of a surface that is fully opaque.
2763 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002765
2766 /*
2767 * visibleRegion: area of a surface that is visible on screen
2768 * and not fully transparent. This is essentially the layer's
2769 * footprint minus the opaque regions above it.
2770 * Areas covered by a translucent surface are considered visible.
2771 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002773
2774 /*
2775 * coveredRegion: area of a surface that is covered by all
2776 * visible regions above it (which includes the translucent areas).
2777 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002779
Jesse Halla8026d22012-09-25 13:25:04 -07002780 /*
2781 * transparentRegion: area of a surface that is hinted to be completely
2782 * transparent. This is only used to tell when the layer has no visible
2783 * non-transparent regions and can be removed from the layer list. It
2784 * does not affect the visibleRegion of this layer or any layers
2785 * beneath it. The hint may not be correct if apps don't respect the
2786 * SurfaceView restrictions (which, sadly, some don't).
2787 */
2788 Region transparentRegion;
2789
Mathias Agopianab028732010-03-16 16:41:46 -07002790
2791 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002792 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002793 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002794 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002795 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002796 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002797 if (!visibleRegion.isEmpty()) {
2798 // Remove the transparent area from the visible region
2799 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002800 if (tr.preserveRects()) {
2801 // transform the transparent region
2802 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002803 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002804 // transformation too complex, can't do the
2805 // transparent region optimization.
2806 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002807 }
Mathias Agopianab028732010-03-16 16:41:46 -07002808 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809
Mathias Agopianab028732010-03-16 16:41:46 -07002810 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002811 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002812 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002813 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2814 // the opaque region is the layer's footprint
2815 opaqueRegion = visibleRegion;
2816 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817 }
2818 }
2819
Robert Carre5f4f692018-01-12 13:12:28 -08002820 if (visibleRegion.isEmpty()) {
2821 layer->clearVisibilityRegions();
2822 return;
2823 }
2824
Mathias Agopianab028732010-03-16 16:41:46 -07002825 // Clip the covered region to the visible region
2826 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2827
2828 // Update aboveCoveredLayers for next (lower) layer
2829 aboveCoveredLayers.orSelf(visibleRegion);
2830
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831 // subtract the opaque region covered by the layers above us
2832 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833
2834 // compute this layer's dirty region
2835 if (layer->contentDirty) {
2836 // we need to invalidate the whole region
2837 dirty = visibleRegion;
2838 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002839 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840 layer->contentDirty = false;
2841 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002842 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002843 * the exposed region consists of two components:
2844 * 1) what's VISIBLE now and was COVERED before
2845 * 2) what's EXPOSED now less what was EXPOSED before
2846 *
2847 * note that (1) is conservative, we start with the whole
2848 * visible region but only keep what used to be covered by
2849 * something -- which mean it may have been exposed.
2850 *
2851 * (2) handles areas that were not covered by anything but got
2852 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002853 */
Mathias Agopianab028732010-03-16 16:41:46 -07002854 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002855 const Region oldVisibleRegion = layer->visibleRegion;
2856 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002857 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2858 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859 }
2860 dirty.subtractSelf(aboveOpaqueLayers);
2861
2862 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002863 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864
Mathias Agopianab028732010-03-16 16:41:46 -07002865 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002867
Jesse Halla8026d22012-09-25 13:25:04 -07002868 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002869 layer->setVisibleRegion(visibleRegion);
2870 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002871 layer->setVisibleNonTransparentRegion(
2872 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002873 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874
Mathias Agopian87baae12012-07-31 12:38:26 -07002875 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876}
2877
Chia-I Wuab0c3192017-08-01 11:29:00 -07002878void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002879 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002880 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002881 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002882 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002883 }
2884 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002885}
2886
Dan Stoza6b9454d2014-11-07 16:00:59 -08002887bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002889 ALOGV("handlePageFlip");
2890
Brian Andersond6927fb2016-07-23 23:37:30 -07002891 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892
Mathias Agopian4fec8732012-06-29 14:12:52 -07002893 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002894 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002895 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002896
2897 // Store the set of layers that need updates. This set must not change as
2898 // buffers are being latched, as this could result in a deadlock.
2899 // Example: Two producers share the same command stream and:
2900 // 1.) Layer 0 is latched
2901 // 2.) Layer 0 gets a new frame
2902 // 2.) Layer 1 gets a new frame
2903 // 3.) Layer 1 is latched.
2904 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2905 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002906 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002907 if (layer->hasQueuedFrame()) {
2908 frameQueued = true;
2909 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002910 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002911 } else {
2912 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002913 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002914 } else {
2915 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002916 }
Robert Carr2047fae2016-11-28 14:09:09 -08002917 });
2918
Dan Stoza9e56aa02015-11-02 13:00:03 -08002919 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002920 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002921 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002922 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002923 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002924 newDataLatched = true;
2925 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002926 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002927
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002928 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002929
2930 // If we will need to wake up at some time in the future to deal with a
2931 // queued frame that shouldn't be displayed during this vsync period, wake
2932 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002933 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002934 signalLayerUpdate();
2935 }
2936
Chia-I Wuad8d8272018-06-26 10:18:18 +08002937 // enter boot animation on first buffer latch
2938 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2939 ALOGI("Enter boot animation");
2940 mBootStage = BootStage::BOOTANIMATION;
2941 }
2942
Dan Stoza6b9454d2014-11-07 16:00:59 -08002943 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002944 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002945}
2946
Mathias Agopianad456f92011-01-13 17:53:01 -08002947void SurfaceFlinger::invalidateHwcGeometry()
2948{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002949 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002950}
2951
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002952
Fabien Sanglard830b8472016-11-30 16:35:58 -08002953void SurfaceFlinger::doDisplayComposition(
2954 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002955 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956{
Dan Stoza71433162014-02-04 16:22:36 -08002957 // We only need to actually compose the display if:
2958 // 1) It is being handled by hardware composer, which may need this to
2959 // keep its virtual display state machine in sync, or
2960 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002961 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002962 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002963 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002964 return;
2965 }
2966
Dan Stoza9e56aa02015-11-02 13:00:03 -08002967 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002968 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002969
2970 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002971 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002972}
2973
Chia-I Wub02087d2017-11-09 10:19:54 -08002974bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002975{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002976 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002977
Chia-I Wub02087d2017-11-09 10:19:54 -08002978 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002979 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002980 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002981 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002982 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002983
Chia-I Wu8e50e692018-05-04 10:12:37 -07002984 bool applyColorMatrix = false;
Chia-I Wu6d844112018-06-27 07:17:41 +08002985 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002986
Dan Stoza9e56aa02015-11-02 13:00:03 -08002987 if (hasClientComposition) {
2988 ALOGV("hasClientComposition");
2989
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002990 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002991 if (displayDevice->hasWideColorGamut()) {
2992 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002993 }
2994 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002995 getBE().mRenderEngine->setDisplayMaxLuminance(
2996 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002997
Chia-I Wu8e50e692018-05-04 10:12:37 -07002998 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2999 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3000 HWC2::Capability::SkipClientColorTransform);
3001
Chia-I Wu6d844112018-06-27 07:17:41 +08003002 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003003 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3004 if (applyColorMatrix) {
Chia-I Wu6d844112018-06-27 07:17:41 +08003005 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003006 }
3007
Chia-I Wu6d844112018-06-27 07:17:41 +08003008 // The current enhanced saturation matrix is designed to enhance Display P3,
3009 // thus we only apply this matrix when the render intent is not colorimetric
3010 // and the output color space is Display P3.
3011 needsEnhancedColorMatrix =
Chia-I Wu0d711262018-05-21 15:19:35 -07003012 (displayDevice->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
Chia-I Wu6d844112018-06-27 07:17:41 +08003013 outputDataspace == Dataspace::DISPLAY_P3);
3014 if (needsEnhancedColorMatrix) {
3015 colorMatrix *= mEnhancedSaturationMatrix;
3016 }
3017
3018 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003019
Chia-I Wu7f402902017-11-09 12:51:10 -08003020 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003021 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003022 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08003023 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003024
3025 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08003026 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07003027 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3028 }
3029 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003030 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003031
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003032 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003033 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003034 // when using overlays, we assume a fully transparent framebuffer
3035 // NOTE: we could reduce how much we need to clear, for instance
3036 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003037 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003038 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003039 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003040 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003041 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003042 // we're left with the letterbox region
3043 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003044 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07003045
3046 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003047 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003048
Mathias Agopianb9494d52012-04-18 02:28:45 -07003049 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003050 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003051 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003052 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003053 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003054 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003055
Yiwei Zhangcf39b7b2018-08-22 13:59:12 -07003056 const Rect& bounds(displayDevice->getBounds());
3057 const Rect& scissor(displayDevice->getScissor());
3058 if (scissor != bounds) {
3059 // scissor doesn't match the screen's dimensions, so we
3060 // need to clear everything outside of it and enable
3061 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003062
Yiwei Zhangcf39b7b2018-08-22 13:59:12 -07003063 // enable scissor for this frame
3064 const uint32_t height = displayDevice->getHeight();
3065 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
3066 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003067 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003068 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003069
Mathias Agopian85d751c2012-08-29 16:59:24 -07003070 /*
3071 * and then, render the layers targeted at the framebuffer
3072 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003073
Dan Stoza9e56aa02015-11-02 13:00:03 -08003074 ALOGV("Rendering client layers");
3075 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003076 bool firstLayer = true;
3077 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3078 const Region clip(bounds.intersect(
3079 displayTransform.transform(layer->visibleRegion)));
3080 ALOGV("Layer: %s", layer->getName().string());
3081 ALOGV(" Composition type: %s",
3082 to_string(layer->getCompositionType(hwcId)).c_str());
3083 if (!clip.isEmpty()) {
3084 switch (layer->getCompositionType(hwcId)) {
3085 case HWC2::Composition::Cursor:
3086 case HWC2::Composition::Device:
3087 case HWC2::Composition::Sideband:
3088 case HWC2::Composition::SolidColor: {
3089 const Layer::State& state(layer->getDrawingState());
3090 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3091 layer->isOpaque(state) && (state.color.a == 1.0f)
3092 && hasClientComposition) {
3093 // never clear the very first layer since we're
3094 // guaranteed the FB is already cleared
3095 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003096 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003097 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003098 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003099 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003100 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003101 break;
3102 }
3103 default:
3104 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003105 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003106 } else {
3107 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003108 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003109 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003110 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003111
Chia-I Wu6d844112018-06-27 07:17:41 +08003112 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003113 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003114 }
3115
Mathias Agopianf45c5102012-10-24 16:29:17 -07003116 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003117 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003118 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003119}
3120
Fabien Sanglard830b8472016-11-30 16:35:58 -08003121void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3122 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003123 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003124 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003125}
3126
Valerie Hauc38310f2019-08-28 14:08:17 -07003127status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3128 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3129 const sp<IBinder>& parentHandle,
3130 const sp<Layer>& parentLayer) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003131 // add this layer to the current state list
3132 {
3133 Mutex::Autolock _l(mStateLock);
Valerie Hauc38310f2019-08-28 14:08:17 -07003134 sp<Layer> parent;
3135
3136 if (parentHandle != nullptr) {
3137 parent = fromHandle(parentHandle);
3138 if (parent == nullptr) {
3139 return NAME_NOT_FOUND;
3140 }
3141 } else {
3142 parent = parentLayer;
3143 }
3144
Robert Carr1f0a16a2016-10-24 16:27:39 -07003145 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003146 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3147 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003148 return NO_MEMORY;
3149 }
Valerie Hauc38310f2019-08-28 14:08:17 -07003150
3151 auto [itr, inserted] = mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3152 if (!inserted) {
3153 ALOGE("-----------ERROR REGISTERING HANDLE, layer pair: handle is already a key");
3154 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003155 if (parent == nullptr) {
3156 mCurrentState.layersSortedByZ.add(lbc);
3157 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003158 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003159 ALOGE("addClientLayer called with a removed parent");
3160 return NAME_NOT_FOUND;
3161 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003162 parent->addChild(lbc);
3163 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003164
Yiwei Zhang243b3782018-05-15 17:40:04 -07003165 if (gbc != nullptr) {
3166 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3167 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3168 mMaxGraphicBufferProducerListSize,
3169 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3170 mGraphicBufferProducerList.size(),
3171 mMaxGraphicBufferProducerListSize, mNumLayers);
3172 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003173 mLayersAdded = true;
3174 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003175 }
3176
Mathias Agopian96f08192010-06-02 23:28:45 -07003177 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003178 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003179
Dan Stoza7d89d062015-04-30 13:29:25 -07003180 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003181}
3182
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003183status_t SurfaceFlinger::removeLayerFromMap(const wp<Layer>& layer) {
Valerie Hauc38310f2019-08-28 14:08:17 -07003184 auto it = mLayersByLocalBinderToken.begin();
3185 while (it != mLayersByLocalBinderToken.end()) {
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003186 if (it->second == layer) {
Valerie Hauc38310f2019-08-28 14:08:17 -07003187 it = mLayersByLocalBinderToken.erase(it);
3188 break;
3189 } else {
3190 it++;
3191 }
3192 }
3193 if (it == mLayersByLocalBinderToken.end()) {
3194 ALOGE("Failed to remove layer from mapping - could not find matching layer");
3195 return BAD_VALUE;
3196 }
3197 return NO_ERROR;
3198}
3199
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003200status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
3201 Mutex::Autolock _l(mStateLock);
3202 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3203}
3204
chaviwca27f252018-02-06 16:46:39 -08003205status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3206 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003207 if (layer->isPendingRemoval()) {
3208 return NO_ERROR;
3209 }
3210
Robert Carr1f0a16a2016-10-24 16:27:39 -07003211 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003212 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003213 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003214 if (topLevelOnly) {
3215 return NO_ERROR;
3216 }
3217
Chia-I Wu98f1c102017-05-30 14:54:08 -07003218 sp<Layer> ancestor = p;
3219 while (ancestor->getParent() != nullptr) {
3220 ancestor = ancestor->getParent();
3221 }
3222 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3223 ALOGE("removeLayer called with a layer whose parent has been removed");
3224 return NAME_NOT_FOUND;
3225 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003226
3227 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003228 } else {
3229 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003230 }
3231
Robert Carr136e2f62017-02-08 17:54:29 -08003232 // As a matter of normal operation, the LayerCleaner will produce a second
3233 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3234 // so we will succeed in promoting it, but it's already been removed
3235 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3236 // otherwise something has gone wrong and we are leaking the layer.
3237 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003238 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3239 layer->getName().string(),
3240 (p != nullptr) ? p->getName().string() : "no-parent");
3241 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003242 } else if (index < 0) {
3243 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003244 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003245
Chia-I Wuc6657022017-08-15 11:18:17 -07003246 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003247 mLayersPendingRemoval.add(layer);
3248 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003249 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003250 setTransactionFlags(eTransactionNeeded);
3251 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252}
3253
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003254uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003255 return android_atomic_release_load(&mTransactionFlags);
3256}
3257
Mathias Agopian3f844832013-08-07 21:24:32 -07003258uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003259 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3260}
3261
Mathias Agopian3f844832013-08-07 21:24:32 -07003262uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003263 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3264}
3265
3266uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3267 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003269 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003270 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003271 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003272 }
3273 return old;
3274}
3275
chaviwca27f252018-02-06 16:46:39 -08003276bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3277 for (const ComposerState& state : states) {
3278 // Here we need to check that the interface we're given is indeed
3279 // one of our own. A malicious client could give us a nullptr
3280 // IInterface, or one of its own or even one of our own but a
3281 // different type. All these situations would cause us to crash.
3282 if (state.client == nullptr) {
3283 return true;
3284 }
3285
3286 sp<IBinder> binder = IInterface::asBinder(state.client);
3287 if (binder == nullptr) {
3288 return true;
3289 }
3290
3291 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3292 return true;
3293 }
3294 }
3295 return false;
3296}
3297
Mathias Agopian8b33f032012-07-24 20:43:54 -07003298void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003299 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003300 const Vector<DisplayState>& displays,
3301 uint32_t flags)
3302{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003303 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003304 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003305 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003306
chaviwca27f252018-02-06 16:46:39 -08003307 if (containsAnyInvalidClientState(states)) {
3308 return;
3309 }
3310
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003311 if (flags & eAnimation) {
3312 // For window updates that are part of an animation we must wait for
3313 // previous animation "frames" to be handled.
3314 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003315 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003316 if (CC_UNLIKELY(err != NO_ERROR)) {
3317 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003318 // caller after a few seconds.
3319 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3320 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003321 mAnimTransactionPending = false;
3322 break;
3323 }
3324 }
3325 }
3326
chaviwca27f252018-02-06 16:46:39 -08003327 for (const DisplayState& display : displays) {
3328 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003329 }
3330
chaviwca27f252018-02-06 16:46:39 -08003331 for (const ComposerState& state : states) {
3332 transactionFlags |= setClientStateLocked(state);
3333 }
3334
3335 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3336 // as destroyed should only occur after setting all other states. This is to allow for a
3337 // child re-parent to happen before marking its original parent as destroyed (which would
3338 // then mark the child as destroyed).
3339 for (const ComposerState& state : states) {
3340 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003341 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003342
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003343 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3344 // anyway. This can be used as a flush mechanism for previous async transactions.
3345 // Empty animation transaction can be used to simulate back-pressure, so also force a
3346 // transaction for empty animation transactions.
3347 if (transactionFlags == 0 &&
3348 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003349 transactionFlags = eTransactionNeeded;
3350 }
3351
Mathias Agopian386aa982011-11-07 21:58:03 -08003352 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003353 if (mInterceptor->isEnabled()) {
3354 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003355 }
Irvel468051e2016-06-13 16:44:44 -07003356
Mathias Agopian386aa982011-11-07 21:58:03 -08003357 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003358 const auto start = (flags & eEarlyWakeup)
3359 ? VSyncModulator::TransactionStart::EARLY
3360 : VSyncModulator::TransactionStart::NORMAL;
3361 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003362
3363 // if this is a synchronous transaction, wait for it to take effect
3364 // before returning.
3365 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003366 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003367 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003368 if (flags & eAnimation) {
3369 mAnimTransactionPending = true;
3370 }
3371 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003372 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3373 if (CC_UNLIKELY(err != NO_ERROR)) {
3374 // just in case something goes wrong in SF, return to the
3375 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003376 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3377 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003378 break;
3379 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003380 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003381 }
3382}
3383
Mathias Agopiane57f2922012-08-09 16:29:12 -07003384uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3385{
Jesse Hall9a143922012-10-04 16:29:19 -07003386 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3387 if (dpyIdx < 0)
3388 return 0;
3389
Mathias Agopiane57f2922012-08-09 16:29:12 -07003390 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003391 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003392 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003393 const uint32_t what = s.what;
3394 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003395 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003396 disp.surface = s.surface;
3397 flags |= eDisplayTransactionNeeded;
3398 }
3399 }
3400 if (what & DisplayState::eLayerStackChanged) {
3401 if (disp.layerStack != s.layerStack) {
3402 disp.layerStack = s.layerStack;
3403 flags |= eDisplayTransactionNeeded;
3404 }
3405 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003406 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003407 if (disp.orientation != s.orientation) {
3408 disp.orientation = s.orientation;
3409 flags |= eDisplayTransactionNeeded;
3410 }
3411 if (disp.frame != s.frame) {
3412 disp.frame = s.frame;
3413 flags |= eDisplayTransactionNeeded;
3414 }
3415 if (disp.viewport != s.viewport) {
3416 disp.viewport = s.viewport;
3417 flags |= eDisplayTransactionNeeded;
3418 }
3419 }
Michael Lentine47e45402014-07-18 15:34:25 -07003420 if (what & DisplayState::eDisplaySizeChanged) {
3421 if (disp.width != s.width) {
3422 disp.width = s.width;
3423 flags |= eDisplayTransactionNeeded;
3424 }
3425 if (disp.height != s.height) {
3426 disp.height = s.height;
3427 flags |= eDisplayTransactionNeeded;
3428 }
3429 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003430 }
3431 return flags;
3432}
3433
Robert Carrd4ae7f32018-06-07 16:10:57 -07003434bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3435 IPCThreadState* ipc = IPCThreadState::self();
3436 const int pid = ipc->getCallingPid();
3437 const int uid = ipc->getCallingUid();
3438
3439 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3440 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3441 return false;
3442 }
3443 return true;
3444}
3445
chaviwca27f252018-02-06 16:46:39 -08003446uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3447 const layer_state_t& s = composerState.state;
3448 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3449
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003450 sp<Layer> layer = fromHandle(s.surface);
3451 if (layer == nullptr || !(client->isAttached(s.surface))) {
chaviw8b3871a2017-11-01 17:41:01 -07003452 return 0;
3453 }
3454
3455 if (layer->isPendingRemoval()) {
3456 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3457 return 0;
3458 }
3459
3460 uint32_t flags = 0;
3461
3462 const uint32_t what = s.what;
3463 bool geometryAppliesWithResize =
3464 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003465
3466 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3467 // pending state will also be deferred.
3468 if (what & layer_state_t::eDeferTransaction) {
3469 layer->pushPendingState();
3470 }
3471
chaviw8b3871a2017-11-01 17:41:01 -07003472 if (what & layer_state_t::ePositionChanged) {
3473 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3474 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003475 }
chaviw8b3871a2017-11-01 17:41:01 -07003476 }
3477 if (what & layer_state_t::eLayerChanged) {
3478 // NOTE: index needs to be calculated before we update the state
3479 const auto& p = layer->getParent();
3480 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003481 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003482 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003483 mCurrentState.layersSortedByZ.removeAt(idx);
3484 mCurrentState.layersSortedByZ.add(layer);
3485 // we need traversal (state changed)
3486 // AND transaction (list changed)
3487 flags |= eTransactionNeeded|eTraversalNeeded;
3488 }
chaviw8b3871a2017-11-01 17:41:01 -07003489 } else {
3490 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003491 flags |= eTransactionNeeded|eTraversalNeeded;
3492 }
3493 }
chaviw8b3871a2017-11-01 17:41:01 -07003494 }
3495 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003496 // NOTE: index needs to be calculated before we update the state
3497 const auto& p = layer->getParent();
3498 if (p == nullptr) {
3499 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3500 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3501 mCurrentState.layersSortedByZ.removeAt(idx);
3502 mCurrentState.layersSortedByZ.add(layer);
3503 // we need traversal (state changed)
3504 // AND transaction (list changed)
3505 flags |= eTransactionNeeded|eTraversalNeeded;
3506 }
3507 } else {
3508 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3509 flags |= eTransactionNeeded|eTraversalNeeded;
3510 }
chaviw8b3871a2017-11-01 17:41:01 -07003511 }
3512 }
3513 if (what & layer_state_t::eSizeChanged) {
3514 if (layer->setSize(s.w, s.h)) {
3515 flags |= eTraversalNeeded;
3516 }
3517 }
3518 if (what & layer_state_t::eAlphaChanged) {
3519 if (layer->setAlpha(s.alpha))
3520 flags |= eTraversalNeeded;
3521 }
3522 if (what & layer_state_t::eColorChanged) {
3523 if (layer->setColor(s.color))
3524 flags |= eTraversalNeeded;
3525 }
3526 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003527 // TODO: b/109894387
3528 //
3529 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3530 // rotation. To see the problem observe that if we have a square parent, and a child
3531 // of the same size, then we rotate the child 45 degrees around it's center, the child
3532 // must now be cropped to a non rectangular 8 sided region.
3533 //
3534 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3535 // private API, and the WindowManager only uses rotation in one case, which is on a top
3536 // level layer in which cropping is not an issue.
3537 //
3538 // However given that abuse of rotation matrices could lead to surfaces extending outside
3539 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3540 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3541 // transformations.
3542 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003543 flags |= eTraversalNeeded;
3544 }
3545 if (what & layer_state_t::eTransparentRegionChanged) {
3546 if (layer->setTransparentRegionHint(s.transparentRegion))
3547 flags |= eTraversalNeeded;
3548 }
3549 if (what & layer_state_t::eFlagsChanged) {
3550 if (layer->setFlags(s.flags, s.mask))
3551 flags |= eTraversalNeeded;
3552 }
3553 if (what & layer_state_t::eCropChanged) {
3554 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3555 flags |= eTraversalNeeded;
3556 }
3557 if (what & layer_state_t::eFinalCropChanged) {
3558 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3559 flags |= eTraversalNeeded;
3560 }
3561 if (what & layer_state_t::eLayerStackChanged) {
3562 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3563 // We only allow setting layer stacks for top level layers,
3564 // everything else inherits layer stack from its parent.
3565 if (layer->hasParent()) {
3566 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3567 layer->getName().string());
3568 } else if (idx < 0) {
3569 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3570 "that also does not appear in the top level layer list. Something"
3571 " has gone wrong.", layer->getName().string());
3572 } else if (layer->setLayerStack(s.layerStack)) {
3573 mCurrentState.layersSortedByZ.removeAt(idx);
3574 mCurrentState.layersSortedByZ.add(layer);
3575 // we need traversal (state changed)
3576 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003577 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003578 }
3579 }
3580 if (what & layer_state_t::eDeferTransaction) {
3581 if (s.barrierHandle != nullptr) {
3582 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3583 } else if (s.barrierGbp != nullptr) {
3584 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3585 if (authenticateSurfaceTextureLocked(gbp)) {
3586 const auto& otherLayer =
3587 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3588 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3589 } else {
3590 ALOGE("Attempt to defer transaction to to an"
3591 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003592 }
3593 }
chaviw8b3871a2017-11-01 17:41:01 -07003594 // We don't trigger a traversal here because if no other state is
3595 // changed, we don't want this to cause any more work
3596 }
3597 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003598 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003599 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003600 if (!hadParent) {
3601 mCurrentState.layersSortedByZ.remove(layer);
3602 }
chaviw8b3871a2017-11-01 17:41:01 -07003603 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003604 }
chaviw8b3871a2017-11-01 17:41:01 -07003605 }
3606 if (what & layer_state_t::eReparentChildren) {
3607 if (layer->reparentChildren(s.reparentHandle)) {
3608 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003609 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003610 }
chaviw8b3871a2017-11-01 17:41:01 -07003611 if (what & layer_state_t::eDetachChildren) {
3612 layer->detachChildren();
3613 }
3614 if (what & layer_state_t::eOverrideScalingModeChanged) {
3615 layer->setOverrideScalingMode(s.overrideScalingMode);
3616 // We don't trigger a traversal here because if no other state is
3617 // changed, we don't want this to cause any more work
3618 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003619 return flags;
3620}
3621
chaviwca27f252018-02-06 16:46:39 -08003622void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3623 const layer_state_t& state = composerState.state;
3624 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3625
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003626 sp<Layer> layer = fromHandle(state.surface);
3627 if (layer == nullptr || !(client->isAttached(state.surface))) {
chaviwca27f252018-02-06 16:46:39 -08003628 return;
3629 }
3630
3631 if (layer->isPendingRemoval()) {
3632 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3633 return;
3634 }
3635
3636 if (state.what & layer_state_t::eDestroySurface) {
3637 removeLayerLocked(mStateLock, layer);
3638 }
3639}
3640
Valerie Hauc38310f2019-08-28 14:08:17 -07003641status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3642 uint32_t h, PixelFormat format, uint32_t flags,
3643 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
3644 sp<IGraphicBufferProducer>* gbp,
3645 const sp<IBinder>& parentHandle,
3646 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003647 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003648 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003649 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003650 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003651 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003652
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003653 status_t result = NO_ERROR;
3654
3655 sp<Layer> layer;
3656
Cody Northropbc755282017-03-31 12:00:08 -06003657 String8 uniqueName = getUniqueLayerName(name);
3658
Mathias Agopian3165cc22012-08-08 19:42:09 -07003659 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3660 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003661 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003662 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003663 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003664
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003665 break;
chaviw13fdc492017-06-27 12:40:18 -07003666 case ISurfaceComposerClient::eFXSurfaceColor:
3667 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003668 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003669 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003670 break;
3671 default:
3672 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003673 break;
3674 }
3675
Dan Stoza7d89d062015-04-30 13:29:25 -07003676 if (result != NO_ERROR) {
3677 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003678 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003679
Chia-I Wuab0c3192017-08-01 11:29:00 -07003680 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3681 // TODO b/64227542
3682 if (windowType == 441731) {
3683 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3684 layer->setPrimaryDisplayOnly();
3685 }
3686
Albert Chaulk479c60c2017-01-27 14:21:34 -05003687 layer->setInfo(windowType, ownerUid);
3688
Valerie Hauc38310f2019-08-28 14:08:17 -07003689 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003690 if (result != NO_ERROR) {
3691 return result;
3692 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003693 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003694
3695 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003696 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003697}
3698
Cody Northropbc755282017-03-31 12:00:08 -06003699String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3700{
3701 bool matchFound = true;
3702 uint32_t dupeCounter = 0;
3703
3704 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3705 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3706
Dan Stoza9fdb7e02018-06-21 12:10:12 -07003707 // Grab the state lock since we're accessing mCurrentState
3708 Mutex::Autolock lock(mStateLock);
3709
Cody Northropbc755282017-03-31 12:00:08 -06003710 // Loop over layers until we're sure there is no matching name
3711 while (matchFound) {
3712 matchFound = false;
Dan Stoza9fdb7e02018-06-21 12:10:12 -07003713 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003714 if (layer->getName() == uniqueName) {
3715 matchFound = true;
3716 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3717 }
3718 });
3719 }
3720
3721 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3722
3723 return uniqueName;
3724}
3725
David Sodman0c69cad2017-08-21 12:12:51 -07003726status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003727 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3728 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003729{
3730 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003731 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003732 case PIXEL_FORMAT_TRANSPARENT:
3733 case PIXEL_FORMAT_TRANSLUCENT:
3734 format = PIXEL_FORMAT_RGBA_8888;
3735 break;
3736 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003737 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003738 break;
3739 }
3740
David Sodman0c69cad2017-08-21 12:12:51 -07003741 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3742 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003743 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003744 *handle = layer->getHandle();
3745 *gbp = layer->getProducer();
3746 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003747 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003748
David Sodman0c69cad2017-08-21 12:12:51 -07003749 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003750 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003751}
3752
chaviw13fdc492017-06-27 12:40:18 -07003753status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003754 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003755 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003756{
chaviw13fdc492017-06-27 12:40:18 -07003757 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003758 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003759 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003760}
3761
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003762status_t SurfaceFlinger::clearLayerFrameStats(const sp<const Client>& client, const sp<IBinder>& handle) {
3763 Mutex::Autolock _l(mStateLock);
3764 sp<Layer> layer = fromHandle(handle);
3765 if (layer == nullptr || !(client->isAttached(handle))) {
3766 return NAME_NOT_FOUND;
3767 }
3768 layer->clearFrameStats();
3769 return NO_ERROR;
3770}
3771
3772status_t SurfaceFlinger::getLayerFrameStats(const sp<const Client>& client, const sp<IBinder>& handle, FrameStats* outStats) {
3773 Mutex::Autolock _l(mStateLock);
3774 sp<Layer> layer = fromHandle(handle);
3775 if (layer == nullptr || !(client->isAttached(handle))) {
3776 return NAME_NOT_FOUND;
3777 }
3778 layer->getFrameStats(outStats);
3779 return NO_ERROR;
3780}
3781
Mathias Agopianac9fa422013-02-11 16:40:36 -08003782status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003783{
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003784 Mutex::Autolock _l(mStateLock);
Robert Carr9524cb32017-02-13 11:32:32 -08003785 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003786 status_t err = NO_ERROR;
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003787 sp<Layer> l = fromHandle(handle);
Valerie Hau01f98632020-07-17 16:59:14 -07003788 if (l != nullptr && client->isAttached(handle)) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003789 mInterceptor->saveSurfaceDeletion(l);
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003790 err = removeLayerLocked(mStateLock, l);
Mathias Agopian67106042013-03-14 19:18:13 -07003791 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3792 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003793 }
3794 return err;
3795}
3796
Mathias Agopian13127d82013-03-05 17:47:11 -08003797status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003798{
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003799 Mutex::Autolock _l(mStateLock);
Mathias Agopian67106042013-03-14 19:18:13 -07003800 // called by ~LayerCleaner() when all references to the IBinder (handle)
3801 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003802 sp<Layer> l = layer.promote();
3803 if (l == nullptr) {
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003804 removeLayerFromMap(layer);
Robert Carr9524cb32017-02-13 11:32:32 -08003805 // The layer has already been removed, carry on
3806 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003807 }
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003808 removeLayerFromMap(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003809 // If we have a parent, then we can continue to live as long as it does.
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003810 return removeLayerLocked(mStateLock, l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003811}
3812
Mathias Agopianb60314a2012-04-10 22:09:54 -07003813// ---------------------------------------------------------------------------
3814
Andy McFadden13a082e2012-08-24 10:16:42 -07003815void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003816 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003817 Vector<ComposerState> state;
3818 Vector<DisplayState> displays;
3819 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003820 d.what = DisplayState::eDisplayProjectionChanged |
3821 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003822 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003823 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003824 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003825 d.frame.makeInvalid();
3826 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003827 d.width = 0;
3828 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003829 displays.add(d);
3830 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003831 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3832 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003833
David Sodman105b7dc2017-11-04 20:28:14 -07003834 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003835 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003836 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003837
Brian Andersond0010582017-03-07 13:20:31 -08003838 // Use phase of 0 since phase is not known.
3839 // Use latency of 0, which will snap to the ideal latency.
3840 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003841}
3842
3843void SurfaceFlinger::initializeDisplays() {
3844 class MessageScreenInitialized : public MessageBase {
3845 SurfaceFlinger* flinger;
3846 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003847 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003848 virtual bool handler() {
3849 flinger->onInitializeDisplays();
3850 return true;
3851 }
3852 };
3853 sp<MessageBase> msg = new MessageScreenInitialized(this);
3854 postMessageAsync(msg); // we may be called from main thread, use async message
3855}
3856
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003857void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003858 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003859 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3860 this);
3861 int32_t type = hw->getDisplayType();
3862 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003863
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003864 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003865 return;
3866 }
3867
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003868 hw->setPowerMode(mode);
3869 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3870 ALOGW("Trying to set power mode for virtual display");
3871 return;
3872 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003873
Lloyd Pique4d234852018-01-22 17:21:36 -08003874 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003875 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003876 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3877 if (idx < 0) {
3878 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3879 return;
3880 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003881 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003882 }
3883
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003884 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003885 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003886 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003887 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3888 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003889 // FIXME: eventthread only knows about the main display right now
3890 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003891 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003892 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003893
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003894 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003895 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003896 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003897
3898 struct sched_param param = {0};
3899 param.sched_priority = 1;
3900 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3901 ALOGW("Couldn't set SCHED_FIFO on display on");
3902 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003903 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003904 // Turn off the display
3905 struct sched_param param = {0};
3906 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3907 ALOGW("Couldn't set SCHED_OTHER on display off");
3908 }
3909
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003910 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3911 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003912 disableHardwareVsync(true); // also cancels any in-progress resync
3913
Mathias Agopiancde87a32012-09-13 14:09:01 -07003914 // FIXME: eventthread only knows about the main display right now
3915 mEventThread->onScreenReleased();
3916 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003917
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003918 getHwComposer().setPowerMode(type, mode);
3919 mVisibleRegionsDirty = true;
3920 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003921 } else if (mode == HWC_POWER_MODE_DOZE ||
3922 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003923 // Update display while dozing
3924 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003925 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3926 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003927 // FIXME: eventthread only knows about the main display right now
3928 mEventThread->onScreenAcquired();
3929 resyncToHardwareVsync(true);
3930 }
3931 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3932 // Leave display going to doze
3933 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3934 disableHardwareVsync(true); // also cancels any in-progress resync
3935 // FIXME: eventthread only knows about the main display right now
3936 mEventThread->onScreenReleased();
3937 }
3938 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003939 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003940 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003941 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003942 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003943 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003944}
3945
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003946void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3947 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003948 SurfaceFlinger& mFlinger;
3949 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003950 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003951 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003952 MessageSetPowerMode(SurfaceFlinger& flinger,
3953 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3954 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003955 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003956 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003957 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003958 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003959 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003960 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003961 ALOGW("Attempt to set power mode = %d for virtual display",
3962 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003963 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003964 mFlinger.setPowerModeInternal(
3965 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003966 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003967 return true;
3968 }
3969 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003970 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003971 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003972}
3973
3974// ---------------------------------------------------------------------------
3975
Lloyd Pique755e3192018-01-31 16:46:15 -08003976status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3977 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003978 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003979
Mathias Agopianbd115332013-04-18 16:41:04 -07003980 IPCThreadState* ipc = IPCThreadState::self();
3981 const int pid = ipc->getCallingPid();
3982 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003983
Mathias Agopianbd115332013-04-18 16:41:04 -07003984 if ((uid != AID_SHELL) &&
3985 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003986 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003987 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003988 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003989 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003990 // (this would indicate SF is stuck, but we want to be able to
3991 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003992 status_t err = mStateLock.timedLock(s2ns(1));
3993 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003994 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003995 result.appendFormat(
3996 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3997 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003998 }
3999
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004000 bool dumpAll = true;
4001 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004002 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004003
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004004 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004005 if ((index < numArgs) &&
4006 (args[index] == String16("--list"))) {
4007 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004008 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004009 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004010 }
4011
4012 if ((index < numArgs) &&
4013 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004014 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004015 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004016 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004017 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004018
4019 if ((index < numArgs) &&
4020 (args[index] == String16("--latency-clear"))) {
4021 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004022 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004023 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004024 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004025
4026 if ((index < numArgs) &&
4027 (args[index] == String16("--dispsync"))) {
4028 index++;
4029 mPrimaryDispSync.dump(result);
4030 dumpAll = false;
4031 }
Dan Stozab90cf072015-03-05 11:05:59 -08004032
4033 if ((index < numArgs) &&
4034 (args[index] == String16("--static-screen"))) {
4035 index++;
4036 dumpStaticScreenStats(result);
4037 dumpAll = false;
4038 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004039
4040 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004041 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004042 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004043 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004044 dumpAll = false;
4045 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004046
4047 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4048 index++;
4049 dumpWideColorInfo(result);
4050 dumpAll = false;
4051 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004052
4053 if ((index < numArgs) &&
4054 (args[index] == String16("--enable-layer-stats"))) {
4055 index++;
4056 mLayerStats.enable();
4057 dumpAll = false;
4058 }
4059
4060 if ((index < numArgs) &&
4061 (args[index] == String16("--disable-layer-stats"))) {
4062 index++;
4063 mLayerStats.disable();
4064 dumpAll = false;
4065 }
4066
4067 if ((index < numArgs) &&
4068 (args[index] == String16("--clear-layer-stats"))) {
4069 index++;
4070 mLayerStats.clear();
4071 dumpAll = false;
4072 }
4073
4074 if ((index < numArgs) &&
4075 (args[index] == String16("--dump-layer-stats"))) {
4076 index++;
4077 mLayerStats.dump(result);
4078 dumpAll = false;
4079 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004080
4081 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4082 index++;
4083 mTimeStats.parseArgs(asProto, args, index, result);
4084 dumpAll = false;
4085 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004086 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004087
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004088 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004089 if (asProto) {
4090 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4091 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4092 } else {
4093 dumpAllLocked(args, index, result);
4094 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004095 }
4096
Mathias Agopian9795c422009-08-26 16:36:26 -07004097 if (locked) {
4098 mStateLock.unlock();
4099 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004100 }
4101 write(fd, result.string(), result.size());
4102 return NO_ERROR;
4103}
4104
Dan Stozac7014012014-02-14 15:03:43 -08004105void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4106 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004107{
Robert Carr2047fae2016-11-28 14:09:09 -08004108 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004109 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004110 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004111}
4112
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004113void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004114 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004115{
4116 String8 name;
4117 if (index < args.size()) {
4118 name = String8(args[index]);
4119 index++;
4120 }
4121
David Sodman105b7dc2017-11-04 20:28:14 -07004122 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004123 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004124 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004125
4126 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004127 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004128 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004129 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004130 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004131 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004132 }
Robert Carr2047fae2016-11-28 14:09:09 -08004133 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004134 }
4135}
4136
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004137void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004138 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004139{
4140 String8 name;
4141 if (index < args.size()) {
4142 name = String8(args[index]);
4143 index++;
4144 }
4145
Robert Carr2047fae2016-11-28 14:09:09 -08004146 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004147 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004148 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004149 }
Robert Carr2047fae2016-11-28 14:09:09 -08004150 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004151
Svetoslavd85084b2014-03-20 10:28:31 -07004152 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004153}
4154
Jamie Gennis6547ff42013-07-16 20:12:42 -07004155// This should only be called from the main thread. Otherwise it would need
4156// the lock and should use mCurrentState rather than mDrawingState.
4157void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004158 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004159 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004160 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004161
4162 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4163}
4164
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004165void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004166{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004167 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004168
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004169 if (isLayerTripleBufferingDisabled())
4170 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004171
4172 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004173 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004174 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004175 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004176 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4177 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004178 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004179}
4180
Dan Stozab90cf072015-03-05 11:05:59 -08004181void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4182{
4183 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004184 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4185 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004186 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004187 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004188 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4189 b + 1, bucketTimeSec, percent);
4190 }
David Sodman4a36e932017-11-07 14:29:47 -08004191 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004192 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004193 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004194 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004195 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004196}
4197
Dan Stozae77c7662016-05-13 11:37:28 -07004198void SurfaceFlinger::recordBufferingStats(const char* layerName,
4199 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004200 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4201 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004202 for (const auto& segment : history) {
4203 if (!segment.usedThirdBuffer) {
4204 stats.twoBufferTime += segment.totalTime;
4205 }
4206 if (segment.occupancyAverage < 1.0f) {
4207 stats.doubleBufferedTime += segment.totalTime;
4208 } else if (segment.occupancyAverage < 2.0f) {
4209 stats.tripleBufferedTime += segment.totalTime;
4210 }
4211 ++stats.numSegments;
4212 stats.totalTime += segment.totalTime;
4213 }
4214}
4215
Brian Andersond6927fb2016-07-23 23:37:30 -07004216void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4217 result.appendFormat("Layer frame timestamps:\n");
4218
4219 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4220 const size_t count = currentLayers.size();
4221 for (size_t i=0 ; i<count ; i++) {
4222 currentLayers[i]->dumpFrameEvents(result);
4223 }
4224}
4225
Dan Stozae77c7662016-05-13 11:37:28 -07004226void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4227 result.append("Buffering stats:\n");
4228 result.append(" [Layer name] <Active time> <Two buffer> "
4229 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004230 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004231 typedef std::tuple<std::string, float, float, float> BufferTuple;
4232 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004233 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004234 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004235 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004236 if (stats.numSegments == 0) {
4237 continue;
4238 }
4239 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4240 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4241 stats.totalTime;
4242 float doubleBufferRatio = static_cast<float>(
4243 stats.doubleBufferedTime) / stats.totalTime;
4244 float tripleBufferRatio = static_cast<float>(
4245 stats.tripleBufferedTime) / stats.totalTime;
4246 sorted.insert({activeTime, {name, twoBufferRatio,
4247 doubleBufferRatio, tripleBufferRatio}});
4248 }
4249 for (const auto& sortedPair : sorted) {
4250 float activeTime = sortedPair.first;
4251 const BufferTuple& values = sortedPair.second;
4252 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4253 std::get<0>(values).c_str(), activeTime,
4254 std::get<1>(values), std::get<2>(values),
4255 std::get<3>(values));
4256 }
4257 result.append("\n");
4258}
4259
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004260void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4261 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004262 result.appendFormat("DisplayColorSetting: %s\n",
4263 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004264
4265 // TODO: print out if wide-color mode is active or not
4266
4267 for (size_t d = 0; d < mDisplays.size(); d++) {
4268 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4269 int32_t hwcId = displayDevice->getHwcDisplayId();
4270 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4271 continue;
4272 }
4273
4274 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004275 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004276 for (auto&& mode : modes) {
4277 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4278 }
4279
Peiyong Lina52f0292018-03-14 17:26:31 -07004280 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004281 result.appendFormat(" Current color mode: %s (%d)\n",
4282 decodeColorMode(currentMode).c_str(), currentMode);
4283 }
4284 result.append("\n");
4285}
4286
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004287LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004288 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004289 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4290 const State& state = useDrawing ? mDrawingState : mCurrentState;
4291 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004292 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004293 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004294 });
4295
4296 return layersProto;
4297}
4298
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004299LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4300 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004301 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004302
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004303 SizeProto* resolution = layersProto.mutable_resolution();
4304 resolution->set_w(displayDevice->getWidth());
4305 resolution->set_h(displayDevice->getHeight());
4306
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004307 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4308 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4309 layersProto.set_global_transform(
4310 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4311
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004312 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004313 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004314 LayerProto* layerProto = layersProto.add_layers();
4315 layer->writeToProto(layerProto, hwcId);
4316 }
4317 });
4318
4319 return layersProto;
4320}
4321
Mathias Agopian74d211a2013-04-22 16:55:35 +02004322void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4323 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004324{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004325 bool colorize = false;
4326 if (index < args.size()
4327 && (args[index] == String16("--color"))) {
4328 colorize = true;
4329 index++;
4330 }
4331
4332 Colorizer colorizer(colorize);
4333
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004334 // figure out if we're stuck somewhere
4335 const nsecs_t now = systemTime();
4336 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4337 const nsecs_t inTransaction(mDebugInTransaction);
4338 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4339 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4340
4341 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004342 * Dump library configuration.
4343 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004344
4345 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004346 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004347 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004348 appendSfConfigString(result);
4349 appendUiConfigString(result);
4350 appendGuiConfigString(result);
4351 result.append("\n");
4352
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004353 result.append("\nWide-Color information:\n");
4354 dumpWideColorInfo(result);
4355
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004356 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004357 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004358 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004359 result.append(SyncFeatures::getInstance().toString());
4360 result.append("\n");
4361
David Sodman105b7dc2017-11-04 20:28:14 -07004362 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004363
Andy McFadden41d67d72014-04-25 16:58:34 -07004364 colorizer.bold(result);
4365 result.append("DispSync configuration: ");
4366 colorizer.reset(result);
Jorim Jaggie203e042018-06-19 15:57:08 +02004367 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4368 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4369 result.appendFormat(
4370 "app phase %" PRId64 " ns, "
4371 "sf phase %" PRId64 " ns, "
4372 "early app phase %" PRId64 " ns, "
4373 "early sf phase %" PRId64 " ns, "
4374 "early app gl phase %" PRId64 " ns, "
4375 "early sf gl phase %" PRId64 " ns, "
4376 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4377 vsyncPhaseOffsetNs,
4378 sfVsyncPhaseOffsetNs,
4379 appEarlyOffset,
4380 sfEarlyOffset,
4381 appEarlyGlOffset,
4382 sfEarlyOffset,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004383 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004384 result.append("\n");
4385
Dan Stozab90cf072015-03-05 11:05:59 -08004386 // Dump static screen stats
4387 result.append("\n");
4388 dumpStaticScreenStats(result);
4389 result.append("\n");
4390
Dan Stozae77c7662016-05-13 11:37:28 -07004391 dumpBufferingStats(result);
4392
Andy McFadden4803b742012-09-24 19:07:20 -07004393 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004394 * Dump the visible layer list
4395 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004396 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004397 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004398 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4399 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004400 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004401
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004402 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004403 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004404 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004405 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004406
4407 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004408 * Dump Display state
4409 */
4410
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004411 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004412 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004413 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004414 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4415 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004416 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004417 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004418 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004419
4420 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004421 * Dump SurfaceFlinger global state
4422 */
4423
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004424 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004425 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004426 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004427
Mathias Agopian888c8222012-08-04 21:10:38 -07004428 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004429 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004430
David Sodmanbc815282017-11-05 18:57:52 -08004431 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004432
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004433 if (hw) {
4434 hw->undefinedRegion.dump(result, "undefinedRegion");
4435 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4436 hw->getOrientation(), hw->isDisplayOn());
4437 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004438 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004439 " last eglSwapBuffers() time: %f us\n"
4440 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004441 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004442 " refresh-rate : %f fps\n"
4443 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004444 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004445 " gpu_to_cpu_unsupported : %d\n"
4446 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004447 mLastSwapBufferTime/1000.0,
4448 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004449 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004450 1e9 / activeConfig->getVsyncPeriod(),
4451 activeConfig->getDpiX(),
4452 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004453 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004454
Mathias Agopian74d211a2013-04-22 16:55:35 +02004455 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004456 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004457
Mathias Agopian74d211a2013-04-22 16:55:35 +02004458 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004459 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004460
4461 /*
4462 * VSYNC state
4463 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004464 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004465 result.append("\n");
4466
4467 /*
Yichi Chen738966b2018-09-15 14:51:18 +08004468 * Tracing state
4469 */
4470 mTracing.dump(result);
4471 result.append("\n");
4472
4473 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004474 * HWC layer minidump
4475 */
4476 for (size_t d = 0; d < mDisplays.size(); d++) {
4477 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4478 int32_t hwcId = displayDevice->getHwcDisplayId();
4479 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4480 continue;
4481 }
4482
4483 result.appendFormat("Display %d HWC layers:\n", hwcId);
4484 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004485 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004486 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004487 });
Dan Stozae22aec72016-08-01 13:20:59 -07004488 result.append("\n");
4489 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004490
4491 /*
4492 * Dump HWComposer state
4493 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004494 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004495 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004496 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004497 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004498 result.appendFormat(" h/w composer %s\n",
4499 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004500 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004501
4502 /*
4503 * Dump gralloc state
4504 */
4505 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4506 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004507
4508 /*
4509 * Dump VrFlinger state if in use.
4510 */
4511 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4512 result.append("VrFlinger state:\n");
4513 result.append(mVrFlinger->Dump().c_str());
4514 result.append("\n");
4515 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004516}
4517
Mathias Agopian13127d82013-03-05 17:47:11 -08004518const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004519SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004520 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004521 wp<IBinder> dpy;
4522 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4523 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4524 dpy = mDisplays.keyAt(i);
4525 break;
4526 }
4527 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004528 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004529 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4530 // Just use the primary display so we have something to return
4531 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4532 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004533 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004534}
4535
Keun young Park63f165f2012-08-31 10:53:36 -07004536bool SurfaceFlinger::startDdmConnection()
4537{
4538 void* libddmconnection_dso =
4539 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4540 if (!libddmconnection_dso) {
4541 return false;
4542 }
4543 void (*DdmConnection_start)(const char* name);
4544 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004545 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004546 if (!DdmConnection_start) {
4547 dlclose(libddmconnection_dso);
4548 return false;
4549 }
4550 (*DdmConnection_start)(getServiceName());
4551 return true;
4552}
4553
Chia-I Wu28f320b2018-05-03 11:02:56 -07004554void SurfaceFlinger::updateColorMatrixLocked() {
4555 mat4 colorMatrix;
4556 if (mGlobalSaturationFactor != 1.0f) {
4557 // Rec.709 luma coefficients
4558 float3 luminance{0.213f, 0.715f, 0.072f};
4559 luminance *= 1.0f - mGlobalSaturationFactor;
4560 mat4 saturationMatrix = mat4(
4561 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4562 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4563 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4564 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4565 );
4566 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4567 } else {
4568 colorMatrix = mClientColorMatrix * mDaltonizer();
4569 }
4570
4571 if (mCurrentState.colorMatrix != colorMatrix) {
4572 mCurrentState.colorMatrix = colorMatrix;
4573 mCurrentState.colorMatrixChanged = true;
4574 setTransactionFlags(eTransactionNeeded);
4575 }
4576}
4577
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004578status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004579 switch (code) {
4580 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004581 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004582 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004583 case CLEAR_ANIMATION_FRAME_STATS:
4584 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004585 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004586 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004587 case ENABLE_VSYNC_INJECTIONS:
4588 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004589 {
4590 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004591 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4592 IPCThreadState* ipc = IPCThreadState::self();
4593 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4594 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004595 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004596 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004597 break;
4598 }
Robert Carr1db73f62016-12-21 12:58:51 -08004599 /*
4600 * Calling setTransactionState is safe, because you need to have been
4601 * granted a reference to Client* and Handle* to do anything with it.
4602 *
4603 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4604 */
4605 case SET_TRANSACTION_STATE:
4606 case CREATE_SCOPED_CONNECTION:
4607 {
4608 return OK;
4609 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004610 case CAPTURE_SCREEN:
4611 {
4612 // codes that require permission check
4613 IPCThreadState* ipc = IPCThreadState::self();
4614 const int pid = ipc->getCallingPid();
4615 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004616 if ((uid != AID_GRAPHICS) &&
4617 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004618 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004619 return PERMISSION_DENIED;
4620 }
4621 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004622 }
chaviwa76b2712017-09-20 12:02:26 -07004623 case CAPTURE_LAYERS: {
4624 IPCThreadState* ipc = IPCThreadState::self();
4625 const int pid = ipc->getCallingPid();
4626 const int uid = ipc->getCallingUid();
4627 if ((uid != AID_GRAPHICS) &&
4628 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4629 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4630 return PERMISSION_DENIED;
4631 }
4632 break;
4633 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004634 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004635 return OK;
4636}
4637
4638status_t SurfaceFlinger::onTransact(
4639 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4640{
4641 status_t credentialCheck = CheckTransactCodeCredentials(code);
4642 if (credentialCheck != OK) {
4643 return credentialCheck;
4644 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004645
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004646 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4647 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004648 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004649 IPCThreadState* ipc = IPCThreadState::self();
4650 const int uid = ipc->getCallingUid();
4651 if (CC_UNLIKELY(uid != AID_SYSTEM
4652 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004653 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004654 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004655 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004656 return PERMISSION_DENIED;
4657 }
4658 int n;
4659 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004660 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004661 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004662 return NO_ERROR;
4663 case 1002: // SHOW_UPDATES
4664 n = data.readInt32();
4665 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004666 invalidateHwcGeometry();
4667 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004668 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004669 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004670 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004671 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004672 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004673 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004674 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004675 setTransactionFlags(
4676 eTransactionNeeded|
4677 eDisplayTransactionNeeded|
4678 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004679 return NO_ERROR;
4680 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004681 case 1006:{ // send empty update
4682 signalRefresh();
4683 return NO_ERROR;
4684 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004685 case 1008: // toggle use of hw composer
4686 n = data.readInt32();
4687 mDebugDisableHWC = n ? 1 : 0;
4688 invalidateHwcGeometry();
4689 repaintEverything();
4690 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004691 case 1009: // toggle use of transform hint
4692 n = data.readInt32();
4693 mDebugDisableTransformHint = n ? 1 : 0;
4694 invalidateHwcGeometry();
4695 repaintEverything();
4696 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004697 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004698 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004699 reply->writeInt32(0);
4700 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004701 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004702 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004703 return NO_ERROR;
4704 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004705 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004706 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004707 return NO_ERROR;
4708 }
4709 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004710 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004711 // daltonize
4712 n = data.readInt32();
4713 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004714 case 1:
4715 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4716 break;
4717 case 2:
4718 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4719 break;
4720 case 3:
4721 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4722 break;
4723 default:
4724 mDaltonizer.setType(ColorBlindnessType::None);
4725 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004726 }
4727 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004728 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004729 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004730 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004731 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004732
4733 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004734 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004735 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004736 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004737 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004738 // apply a color matrix
4739 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004740 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004741 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004742 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004743 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004744 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004745 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004746 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004747 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004748 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004749 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004750
4751 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4752 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004753 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004754 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4755 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4756 }
4757
Chia-I Wu28f320b2018-05-03 11:02:56 -07004758 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004759 return NO_ERROR;
4760 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004761 // This is an experimental interface
4762 // Needs to be shifted to proper binder interface when we productize
4763 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004764 n = data.readInt32();
4765 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004766 return NO_ERROR;
4767 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004768 case 1017: {
4769 n = data.readInt32();
4770 mForceFullDamage = static_cast<bool>(n);
4771 return NO_ERROR;
4772 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004773 case 1018: { // Modify Choreographer's phase offset
4774 n = data.readInt32();
4775 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4776 return NO_ERROR;
4777 }
4778 case 1019: { // Modify SurfaceFlinger's phase offset
4779 n = data.readInt32();
4780 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4781 return NO_ERROR;
4782 }
Irvel468051e2016-06-13 16:44:44 -07004783 case 1020: { // Layer updates interceptor
4784 n = data.readInt32();
4785 if (n) {
4786 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004787 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004788 }
4789 else{
4790 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004791 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004792 }
4793 return NO_ERROR;
4794 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004795 case 1021: { // Disable HWC virtual displays
4796 n = data.readInt32();
4797 mUseHwcVirtualDisplays = !n;
4798 return NO_ERROR;
4799 }
Romain Guy0147a172017-06-01 13:53:56 -07004800 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004801 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004802 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004803
Chia-I Wu28f320b2018-05-03 11:02:56 -07004804 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004805 return NO_ERROR;
4806 }
Romain Guy54f154a2017-10-24 21:40:32 +01004807 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004808 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004809 invalidateHwcGeometry();
4810 repaintEverything();
4811 return NO_ERROR;
4812 }
4813 case 1024: { // Is wide color gamut rendering/color management supported?
4814 reply->writeBool(hasWideColorDisplay);
4815 return NO_ERROR;
4816 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004817 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004818 n = data.readInt32();
4819 if (n) {
Yichi Chen738966b2018-09-15 14:51:18 +08004820 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004821 mTracing.enable();
4822 doTracing("tracing.enable");
4823 reply->writeInt32(NO_ERROR);
4824 } else {
Yichi Chen738966b2018-09-15 14:51:18 +08004825 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004826 status_t err = mTracing.disable();
4827 reply->writeInt32(err);
4828 }
4829 return NO_ERROR;
4830 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004831 case 1026: { // Get layer tracing status
4832 reply->writeBool(mTracing.isEnabled());
4833 return NO_ERROR;
4834 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004835 // Is a DisplayColorSetting supported?
4836 case 1027: {
Chia-I Wu0d711262018-05-21 15:19:35 -07004837 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
4838 if (!hw) {
4839 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004840 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004841
4842 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4843 switch (setting) {
4844 case DisplayColorSetting::MANAGED:
4845 reply->writeBool(hasWideColorDisplay);
4846 break;
4847 case DisplayColorSetting::UNMANAGED:
4848 reply->writeBool(true);
4849 break;
4850 case DisplayColorSetting::ENHANCED:
4851 reply->writeBool(hw->hasRenderIntent(RenderIntent::ENHANCE));
4852 break;
4853 default: // vendor display color setting
4854 reply->writeBool(hw->hasRenderIntent(static_cast<RenderIntent>(setting)));
4855 break;
4856 }
4857 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004858 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004859 }
4860 }
4861 return err;
4862}
4863
Steven Thomas6d8110b2017-08-31 18:24:21 -07004864void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004865 android_atomic_or(1, &mRepaintEverything);
4866 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004867}
4868
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004869// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4870class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004871public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004872 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4873 ~WindowDisconnector() {
4874 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004875 }
4876
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004877private:
4878 ANativeWindow* mWindow;
4879 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004880};
4881
Robert Carra1586de2019-04-02 16:32:58 -07004882status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4883 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004884 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4885 int32_t minLayerZ, int32_t maxLayerZ,
4886 bool useIdentityTransform,
Robert Carr5c999012019-02-19 10:05:00 -08004887 ISurfaceComposer::Rotation rotation,
4888 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004889 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004890
chaviwa76b2712017-09-20 12:02:26 -07004891 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4892
4893 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004894 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4895
Yiwei Zhangf4e02872018-08-20 16:42:23 -07004896 const Rect& dispScissor = device->getScissor();
4897 if (!dispScissor.isEmpty()) {
4898 sourceCrop.set(dispScissor);
4899 // adb shell screencap will default reqWidth and reqHeight to zeros.
4900 if (reqWidth == 0 || reqHeight == 0) {
Yiwei Zhang9ad73bc2018-08-21 22:11:37 -07004901 reqWidth = uint32_t(device->getViewport().width());
4902 reqHeight = uint32_t(device->getViewport().height());
Yiwei Zhangf4e02872018-08-20 16:42:23 -07004903 }
4904 }
4905
Robert Carr5c999012019-02-19 10:05:00 -08004906 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation,
4907 captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004908
4909 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4910 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Robert Carra1586de2019-04-02 16:32:58 -07004911 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform,
4912 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004913}
4914
4915status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004916 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004917 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004918 ATRACE_CALL();
4919
4920 class LayerRenderArea : public RenderArea {
4921 public:
Robert Carr578038f2018-03-09 12:25:24 -08004922 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4923 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004924 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004925 mLayer(layer),
4926 mCrop(crop),
4927 mFlinger(flinger),
4928 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004929 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004930 Rect getBounds() const override {
4931 const Layer::State& layerState(mLayer->getDrawingState());
4932 return Rect(layerState.active.w, layerState.active.h);
4933 }
4934 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4935 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4936 bool isSecure() const override { return false; }
4937 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004938 Rect getSourceCrop() const override {
4939 if (mCrop.isEmpty()) {
4940 return getBounds();
4941 } else {
4942 return mCrop;
4943 }
4944 }
Robert Carr578038f2018-03-09 12:25:24 -08004945 class ReparentForDrawing {
4946 public:
4947 const sp<Layer>& oldParent;
4948 const sp<Layer>& newParent;
4949
4950 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4951 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004952 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004953 }
Robert Carr15eae092018-03-23 13:43:53 -07004954 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004955 };
4956
4957 void render(std::function<void()> drawLayers) override {
4958 if (!mChildrenOnly) {
4959 mTransform = mLayer->getTransform().inverse();
4960 drawLayers();
4961 } else {
4962 Rect bounds = getBounds();
4963 screenshotParentLayer =
4964 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4965 bounds.getWidth(), bounds.getHeight(), 0);
4966
4967 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4968 drawLayers();
4969 }
4970 }
chaviwa76b2712017-09-20 12:02:26 -07004971
chaviwa76b2712017-09-20 12:02:26 -07004972 private:
chaviw7206d492017-11-10 16:16:12 -08004973 const sp<Layer> mLayer;
4974 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004975
4976 // In the "childrenOnly" case we reparent the children to a screenshot
4977 // layer which has no properties set and which does not draw.
4978 sp<ContainerLayer> screenshotParentLayer;
4979 Transform mTransform;
4980
4981 SurfaceFlinger* mFlinger;
4982 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004983 };
4984
Valerie Hauc38310f2019-08-28 14:08:17 -07004985 int reqWidth = 0;
4986 int reqHeight = 0;
4987 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08004988 Rect crop(sourceCrop);
chaviw7206d492017-11-10 16:16:12 -08004989
Valerie Hauc38310f2019-08-28 14:08:17 -07004990 {
4991 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08004992
Valerie Hauc38310f2019-08-28 14:08:17 -07004993 parent = fromHandle(layerHandleBinder);
4994 if (parent == nullptr || parent->isPendingRemoval()) {
4995 ALOGE("captureLayers called with an invalid or removed parent");
4996 return NAME_NOT_FOUND;
4997 }
4998
4999 const int uid = IPCThreadState::self()->getCallingUid();
5000 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5001 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5002 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5003 return PERMISSION_DENIED;
5004 }
5005
5006 if (sourceCrop.width() <= 0) {
5007 crop.left = 0;
5008 crop.right = parent->getCurrentState().active.w;
5009 }
5010
5011 if (sourceCrop.height() <= 0) {
5012 crop.top = 0;
5013 crop.bottom = parent->getCurrentState().active.h;
5014 }
5015
5016 reqWidth = crop.width() * frameScale;
5017 reqHeight = crop.height() * frameScale;
5018 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005019
Robert Carr578038f2018-03-09 12:25:24 -08005020 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005021
Robert Carr578038f2018-03-09 12:25:24 -08005022 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005023 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5024 if (!layer->isVisible()) {
5025 return;
Robert Carr578038f2018-03-09 12:25:24 -08005026 } else if (childrenOnly && layer == parent.get()) {
5027 return;
chaviwa76b2712017-09-20 12:02:26 -07005028 }
5029 visitor(layer);
5030 });
5031 };
Robert Carra1586de2019-04-02 16:32:58 -07005032 bool outCapturedSecureLayers = false;
5033 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false,
5034 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005035}
5036
5037status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5038 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005039 sp<GraphicBuffer>* outBuffer,
Robert Carra1586de2019-04-02 16:32:58 -07005040 bool useIdentityTransform,
5041 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005042 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005043
Iris Chang7501ed62018-04-30 14:45:42 +08005044 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005045
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005046 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5047 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5048 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5049 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005050
5051 // This mutex protects syncFd and captureResult for communication of the return values from the
5052 // main thread back to this Binder thread
5053 std::mutex captureMutex;
5054 std::condition_variable captureCondition;
5055 std::unique_lock<std::mutex> captureLock(captureMutex);
5056 int syncFd = -1;
5057 std::optional<status_t> captureResult;
5058
Robert Carr03480e22018-01-04 16:02:06 -08005059 const int uid = IPCThreadState::self()->getCallingUid();
5060 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5061
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005062 sp<LambdaMessage> message = new LambdaMessage([&]() {
5063 // If there is a refresh pending, bug out early and tell the binder thread to try again
5064 // after the refresh.
5065 if (mRefreshPending) {
5066 ATRACE_NAME("Skipping screenshot for now");
5067 std::unique_lock<std::mutex> captureLock(captureMutex);
5068 captureResult = std::make_optional<status_t>(EAGAIN);
5069 captureCondition.notify_one();
5070 return;
5071 }
5072
5073 status_t result = NO_ERROR;
5074 int fd = -1;
5075 {
5076 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08005077 renderArea.render([&]() {
5078 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
Robert Carra1586de2019-04-02 16:32:58 -07005079 useIdentityTransform, forSystem, &fd,
5080 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005081 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005082 }
5083
5084 {
5085 std::unique_lock<std::mutex> captureLock(captureMutex);
5086 syncFd = fd;
5087 captureResult = std::make_optional<status_t>(result);
5088 captureCondition.notify_one();
5089 }
5090 });
5091
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005092 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005093 if (result == NO_ERROR) {
5094 captureCondition.wait(captureLock, [&]() { return captureResult; });
5095 while (*captureResult == EAGAIN) {
5096 captureResult.reset();
5097 result = postMessageAsync(message);
5098 if (result != NO_ERROR) {
5099 return result;
5100 }
5101 captureCondition.wait(captureLock, [&]() { return captureResult; });
5102 }
5103 result = *captureResult;
5104 }
5105
5106 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005107 sync_wait(syncFd, -1);
5108 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005109 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005110
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005111 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005112}
5113
chaviwa76b2712017-09-20 12:02:26 -07005114void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5115 TraverseLayersFunction traverseLayers, bool yswap,
5116 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005117 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005118
Lloyd Pique144e1162017-12-20 16:44:52 -08005119 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005120
5121 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005122 const auto raWidth = renderArea.getWidth();
5123 const auto raHeight = renderArea.getHeight();
5124
5125 const auto reqWidth = renderArea.getReqWidth();
5126 const auto reqHeight = renderArea.getReqHeight();
5127 Rect sourceCrop = renderArea.getSourceCrop();
5128
Iris Chang7501ed62018-04-30 14:45:42 +08005129 bool filtering = false;
5130 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5131 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5132 static_cast<int32_t>(reqHeight) != raWidth;
5133 } else {
5134 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5135 static_cast<int32_t>(reqHeight) != raHeight;
5136 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005137
Dan Stozac1879002014-05-22 15:59:05 -07005138 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005139 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005140 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005141 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005142 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5143 Transform tr;
5144 uint32_t flags = 0x00;
5145 switch (mPrimaryDisplayOrientation) {
5146 case DisplayState::eOrientation90:
5147 flags = Transform::ROT_90;
5148 break;
5149 case DisplayState::eOrientation180:
5150 flags = Transform::ROT_180;
5151 break;
5152 case DisplayState::eOrientation270:
5153 flags = Transform::ROT_270;
5154 break;
5155 }
5156 tr.set(flags, raWidth, raHeight);
5157 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005158 }
5159
5160 // ensure that sourceCrop is inside screen
5161 if (sourceCrop.left < 0) {
5162 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5163 }
chaviwa76b2712017-09-20 12:02:26 -07005164 if (sourceCrop.right > raWidth) {
5165 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005166 }
5167 if (sourceCrop.top < 0) {
5168 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5169 }
chaviwa76b2712017-09-20 12:02:26 -07005170 if (sourceCrop.bottom > raHeight) {
5171 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005172 }
5173
Chia-I Wu36574d92018-05-16 10:54:36 -07005174 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5175 engine.setOutputDataSpace(Dataspace::SRGB);
5176 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005177
Mathias Agopian180f10d2013-04-10 22:55:41 -07005178 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005179 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005180
Iris Chang7501ed62018-04-30 14:45:42 +08005181 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5182 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5183 // convert hw orientation into flag presentation
5184 // here inverse transform needed
5185 uint8_t hw_rot_90 = 0x00;
5186 uint8_t hw_flip_hv = 0x00;
5187 switch (mPrimaryDisplayOrientation) {
5188 case DisplayState::eOrientation90:
5189 hw_rot_90 = Transform::ROT_90;
5190 hw_flip_hv = Transform::ROT_180;
5191 break;
5192 case DisplayState::eOrientation180:
5193 hw_flip_hv = Transform::ROT_180;
5194 break;
5195 case DisplayState::eOrientation270:
5196 hw_rot_90 = Transform::ROT_90;
5197 break;
5198 }
5199
5200 // transform flags operation
5201 // 1) flip H V if both have ROT_90 flag
5202 // 2) XOR these flags
5203 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5204 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5205 if (rotation_rot_90 & hw_rot_90) {
5206 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5207 }
5208 rotation = static_cast<Transform::orientation_flags>
5209 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5210 }
5211
Mathias Agopian180f10d2013-04-10 22:55:41 -07005212 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005213 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005214 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005215 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005216
chaviw50da5042018-04-09 13:49:37 -07005217 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005218 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005219 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005220
chaviwa76b2712017-09-20 12:02:26 -07005221 traverseLayers([&](Layer* layer) {
5222 if (filtering) layer->setFiltering(true);
5223 layer->draw(renderArea, useIdentityTransform);
5224 if (filtering) layer->setFiltering(false);
5225 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005226}
5227
chaviwa76b2712017-09-20 12:02:26 -07005228status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5229 TraverseLayersFunction traverseLayers,
5230 ANativeWindowBuffer* buffer,
Robert Carra1586de2019-04-02 16:32:58 -07005231 bool useIdentityTransform, bool forSystem,
5232 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005233 ATRACE_CALL();
5234
chaviwa76b2712017-09-20 12:02:26 -07005235 traverseLayers([&](Layer* layer) {
Robert Carra1586de2019-04-02 16:32:58 -07005236 outCapturedSecureLayers =
5237 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005238 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005239
Robert Carr03480e22018-01-04 16:02:06 -08005240 // We allow the system server to take screenshots of secure layers for
5241 // use in situations like the Screen-rotation animation and place
5242 // the impetus on WindowManager to not persist them.
Robert Carra1586de2019-04-02 16:32:58 -07005243 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005244 ALOGW("FB is protected: PERMISSION_DENIED");
5245 return PERMISSION_DENIED;
5246 }
5247
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005248 // this binds the given EGLImage as a framebuffer for the
5249 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005250 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005251 if (bufferBond.getStatus() != NO_ERROR) {
5252 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005253 return INVALID_OPERATION;
5254 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005255
Dan Stozaabcda352017-06-01 14:37:39 -07005256 // this will in fact render into our dequeued buffer
5257 // via an FBO, which means we didn't have to create
5258 // an EGLSurface and therefore we're not
5259 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005260 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005261
Dan Stozaabcda352017-06-01 14:37:39 -07005262 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005263 getRenderEngine().finish();
5264 *outSyncFd = -1;
5265
chaviwa76b2712017-09-20 12:02:26 -07005266 const auto reqWidth = renderArea.getReqWidth();
5267 const auto reqHeight = renderArea.getReqHeight();
5268
Dan Stozaabcda352017-06-01 14:37:39 -07005269 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5270 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005271 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005272 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005273 } else {
5274 base::unique_fd syncFd = getRenderEngine().flush();
5275 if (syncFd < 0) {
5276 getRenderEngine().finish();
5277 }
5278 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005279 }
5280
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005281 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005282}
5283
Mathias Agopiand5556842013-09-19 17:08:37 -07005284void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005285 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005286 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005287 for (size_t y = 0; y < h; y++) {
5288 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5289 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005290 if (p[x] != 0xFF000000) return;
5291 }
5292 }
chaviwa76b2712017-09-20 12:02:26 -07005293 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005294
Robert Carr2047fae2016-11-28 14:09:09 -08005295 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005296 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005297 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005298 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5299 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5300 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5301 static_cast<float>(state.color.a));
5302 i++;
5303 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005304 }
5305}
5306
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005307// ---------------------------------------------------------------------------
5308
Dan Stoza412903f2017-04-27 13:42:17 -07005309void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5310 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005311}
5312
Dan Stoza412903f2017-04-27 13:42:17 -07005313void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5314 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005315}
5316
chaviwa76b2712017-09-20 12:02:26 -07005317void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5318 int32_t maxLayerZ,
5319 const LayerVector::Visitor& visitor) {
5320 // We loop through the first level of layers without traversing,
5321 // as we need to interpret min/max layer Z in the top level Z space.
5322 for (const auto& layer : mDrawingState.layersSortedByZ) {
5323 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5324 continue;
5325 }
5326 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005327 // relative layers are traversed in Layer::traverseInZOrder
5328 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005329 continue;
5330 }
5331 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005332 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5333 return;
5334 }
chaviwa76b2712017-09-20 12:02:26 -07005335 if (!layer->isVisible()) {
5336 return;
5337 }
5338 visitor(layer);
5339 });
5340 }
5341}
5342
Valerie Hauc38310f2019-08-28 14:08:17 -07005343sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5344 BBinder *b = handle->localBinder();
5345 if (b == nullptr) {
5346 return nullptr;
5347 }
5348 auto it = mLayersByLocalBinderToken.find(b);
5349 if (it != mLayersByLocalBinderToken.end()) {
5350 auto ret = it->second.promote();
5351 return ret;
5352 }
5353 return nullptr;
5354}
Mathias Agopian3f844832013-08-07 21:24:32 -07005355
Valerie Hauc38310f2019-08-28 14:08:17 -07005356} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005357
5358#if defined(__gl_h_)
5359#error "don't include gl/gl.h in this file"
5360#endif
5361
5362#if defined(__gl2_h_)
5363#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005364#endif