blob: 196c6ea5847788027881655db850973d9f5be812 [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
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.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 Lin9f034472018-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 Pique99d3da52018-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 Piqueac648ee2018-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()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700222 mDisplayTokens(),
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),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700227 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700228 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700229 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700230 mDebugInSwapBuffers(0),
231 mLastSwapBufferTime(0),
232 mDebugInTransaction(0),
233 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700234 mBootFinished(false),
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 Pique99d3da52018-01-22 17:48:03 -0800243 mCreateBufferQueue(&BufferQueue::createBufferQueue),
244 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-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 Jaggi22ec38b2018-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 Stoza84d619e2018-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 Pique3fcdef12018-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);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700436 DisplayDeviceState info;
437 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700438 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700439 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800441 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700442 return token;
443}
444
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700445void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700446 Mutex::Autolock _l(mStateLock);
447
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700448 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700449 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700450 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700451 return;
452 }
453
454 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700455 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700456 ALOGE("destroyDisplay called for non-virtual display");
457 return;
458 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700459 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700460 mCurrentState.displays.removeItemsAt(idx);
461 setTransactionFlags(eDisplayTransactionNeeded);
462}
463
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700465 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700466 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800467 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700468 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700469 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470}
471
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800472void SurfaceFlinger::bootFinished()
473{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700474 if (mStartPropertySetThread->join() != NO_ERROR) {
475 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800476 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800477 const nsecs_t now = systemTime();
478 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000479 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700480
481 // wait patiently for the window manager death
482 const String16 name("window");
483 sp<IBinder> window(defaultServiceManager()->getService(name));
484 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700485 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700486 }
487
Steven Thomas050b2c82017-03-06 11:45:16 -0800488 if (mVrFlinger) {
489 mVrFlinger->OnBootFinished();
490 }
491
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700492 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700493 // formerly we would just kill the process, but we now ask it to exit so it
494 // can choose where to stop the animation.
495 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700496
497 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
498 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
499 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700500
Dominik Laskowski8c001672018-05-30 16:52:06 -0700501 postMessageAsync(new LambdaMessage([this] { readPersistentProperties(); }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800502}
503
Dan Stoza436ccf32018-06-21 12:10:12 -0700504uint32_t SurfaceFlinger::getNewTexture() {
505 {
506 std::lock_guard lock(mTexturePoolMutex);
507 if (!mTexturePool.empty()) {
508 uint32_t name = mTexturePool.back();
509 mTexturePool.pop_back();
510 ATRACE_INT("TexturePoolSize", mTexturePool.size());
511 return name;
512 }
513
514 // The pool was too small, so increase it for the future
515 ++mTexturePoolSize;
516 }
517
518 // The pool was empty, so we need to get a new texture name directly using a
519 // blocking call to the main thread
520 uint32_t name = 0;
521 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
522 return name;
523}
524
Mathias Agopian3f844832013-08-07 21:24:32 -0700525void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700526 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700527}
528
Lloyd Piquee83f9312018-02-01 12:53:17 -0800529class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700531 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000532 const char* name) :
533 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700534 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700535 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000536 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
537 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700538 mDispSync(dispSync),
539 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700540 mVsyncMutex(),
541 mPhaseOffset(phaseOffset),
542 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700543
Lloyd Piquee83f9312018-02-01 12:53:17 -0800544 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700545
Lloyd Piquee83f9312018-02-01 12:53:17 -0800546 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700547 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700548 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000549 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700550 static_cast<DispSync::Callback*>(this));
551 if (err != NO_ERROR) {
552 ALOGE("error registering vsync callback: %s (%d)",
553 strerror(-err), err);
554 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700555 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700556 } else {
557 status_t err = mDispSync->removeEventListener(
558 static_cast<DispSync::Callback*>(this));
559 if (err != NO_ERROR) {
560 ALOGE("error unregistering vsync callback: %s (%d)",
561 strerror(-err), err);
562 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700563 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700564 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700565 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700566 }
567
Lloyd Piquee83f9312018-02-01 12:53:17 -0800568 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700569 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700570 mCallback = callback;
571 }
572
Lloyd Piquee83f9312018-02-01 12:53:17 -0800573 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700574 Mutex::Autolock lock(mVsyncMutex);
575
576 // Normalize phaseOffset to [0, period)
577 auto period = mDispSync->getPeriod();
578 phaseOffset %= period;
579 if (phaseOffset < 0) {
580 // If we're here, then phaseOffset is in (-period, 0). After this
581 // operation, it will be in (0, period)
582 phaseOffset += period;
583 }
584 mPhaseOffset = phaseOffset;
585
586 // If we're not enabled, we don't need to mess with the listeners
587 if (!mEnabled) {
588 return;
589 }
590
Dan Stoza84d619e2018-03-28 17:07:36 -0700591 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
592 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700593 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700594 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700595 strerror(-err), err);
596 }
597 }
598
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700599private:
600 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800601 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700603 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604 callback = mCallback;
605
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700606 if (mTraceVsync) {
607 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700608 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700609 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700610 }
611
Peiyong Lin566a3b42018-01-09 18:22:43 -0800612 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700613 callback->onVSyncEvent(when);
614 }
615 }
616
Tim Murray4a4e4a22016-04-19 16:29:23 +0000617 const char* const mName;
618
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700619 int mValue;
620
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700621 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700622 const String8 mVsyncOnLabel;
623 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700624
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700625 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700626
627 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800628 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700629
630 Mutex mVsyncMutex; // Protects the following
631 nsecs_t mPhaseOffset;
632 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700633};
634
Lloyd Piquee83f9312018-02-01 12:53:17 -0800635class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700636public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800637 InjectVSyncSource() = default;
638 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700639
Lloyd Piquee83f9312018-02-01 12:53:17 -0800640 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700641 std::lock_guard<std::mutex> lock(mCallbackMutex);
642 mCallback = callback;
643 }
644
Lloyd Piquee83f9312018-02-01 12:53:17 -0800645 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700646 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700647 if (mCallback) {
648 mCallback->onVSyncEvent(when);
649 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700650 }
651
Lloyd Piquee83f9312018-02-01 12:53:17 -0800652 void setVSyncEnabled(bool) override {}
653 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700654
655private:
656 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800657 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700658};
659
Wei Wangf9b05ee2017-07-19 20:59:39 -0700660// Do not call property_set on main thread which will be blocked by init
661// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700662void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700663 ALOGI( "SurfaceFlinger's main thread ready to run. "
664 "Initializing graphics H/W...");
665
Thierry Strudel2924d012017-08-14 15:19:37 -0700666 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900667
Steven Thomasb02664d2017-07-26 18:48:28 -0700668 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800669
Steven Thomasb02664d2017-07-26 18:48:28 -0700670 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800671 mEventThreadSource =
672 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
673 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800674 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700675 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800676 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800677 "appEventThread");
678 mSfEventThreadSource =
679 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
680 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800681
Lloyd Pique24b0a482018-03-09 18:52:26 -0800682 mSFEventThread =
683 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700684 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800685 [this](nsecs_t timestamp) {
686 mInterceptor->saveVSyncEvent(timestamp);
687 },
688 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800689 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200690 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800691
Steven Thomasb02664d2017-07-26 18:48:28 -0700692 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800693 getBE().mRenderEngine =
694 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
695 hasWideColorDisplay
696 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
697 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800698 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700699
700 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
701 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800702 getBE().mHwc.reset(
703 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700704 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800705 // Process any initial hotplug and resulting display changes.
706 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700707 const auto display = getDefaultDisplayDeviceLocked();
708 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
709 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
710 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800711
Lloyd Piquefcd86612017-12-14 17:15:36 -0800712 // make the default display GLContext current so that we can create textures
713 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700714 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800715
Steven Thomas050b2c82017-03-06 11:45:16 -0800716 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700717 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700718 // This callback is called from the vr flinger dispatch thread. We
719 // need to call signalTransaction(), which requires holding
720 // mStateLock when we're not on the main thread. Acquiring
721 // mStateLock from the vr flinger dispatch thread might trigger a
722 // deadlock in surface flinger (see b/66916578), so post a message
723 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700724 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700725 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
726 mVrFlingerRequestsDisplay = requestDisplay;
727 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700728 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800729 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700730 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
731 getHwComposer()
732 .getHwcDisplayId(display->getId())
733 .value_or(0),
734 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800735 if (!mVrFlinger) {
736 ALOGE("Failed to start vrflinger");
737 }
738 }
739
Lloyd Pique379adc12018-01-22 17:31:47 -0800740 mEventControlThread = std::make_unique<impl::EventControlThread>(
741 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700742
Mathias Agopian92a979a2012-08-02 18:32:23 -0700743 // initialize our drawing state
744 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700745
Andy McFadden13a082e2012-08-24 10:16:42 -0700746 // set initial conditions (e.g. unblank default device)
747 initializeDisplays();
748
David Sodmanbc815282017-11-05 18:57:52 -0800749 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700750
Wei Wangf9b05ee2017-07-19 20:59:39 -0700751 // Inform native graphics APIs whether the present timestamp is supported:
752 if (getHwComposer().hasCapability(
753 HWC2::Capability::PresentFenceIsNotReliable)) {
754 mStartPropertySetThread = new StartPropertySetThread(false);
755 } else {
756 mStartPropertySetThread = new StartPropertySetThread(true);
757 }
758
759 if (mStartPropertySetThread->Start() != NO_ERROR) {
760 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800761 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800762
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700763 mLegacySrgbSaturationMatrix =
764 getHwComposer().getDataspaceSaturationMatrix(display->getId(), Dataspace::SRGB_LINEAR);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800765
Dan Stoza9e56aa02015-11-02 13:00:03 -0800766 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700767}
768
Romain Guy11d63f42017-07-20 12:47:14 -0700769void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700770 Mutex::Autolock _l(mStateLock);
771
Romain Guy11d63f42017-07-20 12:47:14 -0700772 char value[PROPERTY_VALUE_MAX];
773
774 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800775 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700776 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800777 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100778
779 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700780 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700781}
782
Mathias Agopiana67e4182012-06-19 17:26:12 -0700783void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800784 // Start boot animation service by setting a property mailbox
785 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700786 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800787 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700788 if (mStartPropertySetThread->join() != NO_ERROR) {
789 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800790 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700791}
792
Mathias Agopian875d8e12013-06-07 15:35:48 -0700793size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800794 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700795}
796
Mathias Agopian875d8e12013-06-07 15:35:48 -0700797size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800798 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700799}
800
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800801// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800802
Jamie Gennis582270d2011-08-17 18:19:00 -0700803bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800804 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800805 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800806 return authenticateSurfaceTextureLocked(bufferProducer);
807}
808
809bool SurfaceFlinger::authenticateSurfaceTextureLocked(
810 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800811 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800812 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800813}
814
Brian Anderson6b376712017-04-04 10:51:39 -0700815status_t SurfaceFlinger::getSupportedFrameTimestamps(
816 std::vector<FrameEvent>* outSupported) const {
817 *outSupported = {
818 FrameEvent::REQUESTED_PRESENT,
819 FrameEvent::ACQUIRE,
820 FrameEvent::LATCH,
821 FrameEvent::FIRST_REFRESH_START,
822 FrameEvent::LAST_REFRESH_START,
823 FrameEvent::GPU_COMPOSITION_DONE,
824 FrameEvent::DEQUEUE_READY,
825 FrameEvent::RELEASE,
826 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700827 ConditionalLock _l(mStateLock,
828 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700829 if (!getHwComposer().hasCapability(
830 HWC2::Capability::PresentFenceIsNotReliable)) {
831 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
832 }
833 return NO_ERROR;
834}
835
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700836status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
837 Vector<DisplayInfo>* configs) {
838 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 return BAD_VALUE;
840 }
841
Jesse Hall692c7232012-11-08 15:41:56 -0800842 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700843 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
844 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700845 type = i;
846 break;
847 }
848 }
849
850 if (type < 0) {
851 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700852 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700853
Mathias Agopian8b736f12012-08-13 17:54:26 -0700854 // TODO: Not sure if display density should handled by SF any longer
855 class Density {
856 static int getDensityFromProperty(char const* propName) {
857 char property[PROPERTY_VALUE_MAX];
858 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800859 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700860 density = atoi(property);
861 }
862 return density;
863 }
864 public:
865 static int getEmuDensity() {
866 return getDensityFromProperty("qemu.sf.lcd_density"); }
867 static int getBuildDensity() {
868 return getDensityFromProperty("ro.sf.lcd_density"); }
869 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700870
Dan Stoza7f7da322014-05-02 15:26:25 -0700871 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700872
Steven Thomas6d8110b2017-08-31 18:24:21 -0700873 ConditionalLock _l(mStateLock,
874 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800875 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700876 DisplayInfo info = DisplayInfo();
877
Dan Stoza9e56aa02015-11-02 13:00:03 -0800878 float xdpi = hwConfig->getDpiX();
879 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700880
881 if (type == DisplayDevice::DISPLAY_PRIMARY) {
882 // The density of the device is provided by a build property
883 float density = Density::getBuildDensity() / 160.0f;
884 if (density == 0) {
885 // the build doesn't provide a density -- this is wrong!
886 // use xdpi instead
887 ALOGE("ro.sf.lcd_density must be defined as a build property");
888 density = xdpi / 160.0f;
889 }
890 if (Density::getEmuDensity()) {
891 // if "qemu.sf.lcd_density" is specified, it overrides everything
892 xdpi = ydpi = density = Density::getEmuDensity();
893 density /= 160.0f;
894 }
895 info.density = density;
896
897 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700898 const auto display = getDefaultDisplayDeviceLocked();
899 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700900 } else {
901 // TODO: where should this value come from?
902 static const int TV_DENSITY = 213;
903 info.density = TV_DENSITY / 160.0f;
904 info.orientation = 0;
905 }
906
Dan Stoza9e56aa02015-11-02 13:00:03 -0800907 info.w = hwConfig->getWidth();
908 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700909 info.xdpi = xdpi;
910 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800911 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900912 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800913
Andy McFadden91b2ca82014-06-13 14:04:23 -0700914 // This is how far in advance a buffer must be queued for
915 // presentation at a given time. If you want a buffer to appear
916 // on the screen at time N, you must submit the buffer before
917 // (N - presentationDeadline).
918 //
919 // Normally it's one full refresh period (to give SF a chance to
920 // latch the buffer), but this can be reduced by configuring a
921 // DispSync offset. Any additional delays introduced by the hardware
922 // composer or panel must be accounted for here.
923 //
924 // We add an additional 1ms to allow for processing time and
925 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800926 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800927 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700928
929 // All non-virtual displays are currently considered secure.
930 info.secure = true;
931
Iris Chang7501ed62018-04-30 14:45:42 +0800932 if (type == DisplayDevice::DISPLAY_PRIMARY &&
933 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
934 std::swap(info.w, info.h);
935 }
936
Michael Wright28f24d02016-07-12 13:30:53 -0700937 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700938 }
939
Dan Stoza7f7da322014-05-02 15:26:25 -0700940 return NO_ERROR;
941}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
944 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700945 return BAD_VALUE;
946 }
947
948 // FIXME for now we always return stats for the primary display
949 memset(stats, 0, sizeof(*stats));
950 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
951 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
952 return NO_ERROR;
953}
954
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700955int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
956 const auto display = getDisplayDevice(displayToken);
957 if (!display) {
958 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800959 return BAD_VALUE;
960 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700961
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700963}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700964
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700965void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
966 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700967 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700968 return;
969 }
970
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700971 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700972 ALOGW("Trying to set config for virtual display");
973 return;
974 }
975
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700976 display->setActiveConfig(mode);
977 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700978}
979
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700980status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700981 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700982 Vector<DisplayInfo> configs;
983 getDisplayConfigs(displayToken, &configs);
984 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
985 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
986 configs.size());
987 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700988 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700989 const auto display = getDisplayDevice(displayToken);
990 if (!display) {
991 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
992 displayToken.get());
993 } else if (display->isVirtual()) {
994 ALOGW("Attempt to set active config %d for virtual display", mode);
995 } else {
996 setActiveConfigInternal(display, mode);
997 }
998 }));
999
Mathias Agopian888c8222012-08-04 21:10:38 -07001000 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001001}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001002status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1003 Vector<ColorMode>* outColorModes) {
1004 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001005 return BAD_VALUE;
1006 }
1007
Michael Wright28f24d02016-07-12 13:30:53 -07001008 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1010 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001011 type = i;
1012 break;
1013 }
1014 }
1015
1016 if (type < 0) {
1017 return type;
1018 }
1019
Peiyong Lina52f0292018-03-14 17:26:31 -07001020 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001021 {
1022 ConditionalLock _l(mStateLock,
1023 std::this_thread::get_id() != mMainThreadId);
1024 modes = getHwComposer().getColorModes(type);
1025 }
Michael Wright28f24d02016-07-12 13:30:53 -07001026 outColorModes->clear();
1027 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1028
1029 return NO_ERROR;
1030}
1031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1033 if (const auto display = getDisplayDevice(displayToken)) {
1034 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001035 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001036 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001037}
1038
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001039void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1040 Dataspace dataSpace, RenderIntent renderIntent) {
1041 ColorMode currentMode = display->getActiveColorMode();
1042 Dataspace currentDataSpace = display->getCompositionDataSpace();
1043 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001044
Peiyong Lin38e9a562018-04-10 16:24:20 -07001045 if (mode == currentMode && dataSpace == currentDataSpace &&
1046 renderIntent == currentRenderIntent) {
1047 return;
1048 }
1049
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001051 ALOGW("Trying to set config for virtual display");
1052 return;
1053 }
1054
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055 display->setActiveColorMode(mode);
1056 display->setCompositionDataSpace(dataSpace);
1057 display->setActiveRenderIntent(renderIntent);
1058 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001059
1060 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001061 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1062 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001063}
1064
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001065status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001066 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001067 Vector<ColorMode> modes;
1068 getDisplayColorModes(displayToken, &modes);
1069 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1070 if (mode < ColorMode::NATIVE || !exists) {
1071 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1072 decodeColorMode(mode).c_str(), mode, displayToken.get());
1073 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001074 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001075 const auto display = getDisplayDevice(displayToken);
1076 if (!display) {
1077 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1078 decodeColorMode(mode).c_str(), mode, displayToken.get());
1079 } else if (display->isVirtual()) {
1080 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1081 decodeColorMode(mode).c_str(), mode);
1082 } else {
1083 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1084 RenderIntent::COLORIMETRIC);
1085 }
1086 }));
1087
Michael Wright28f24d02016-07-12 13:30:53 -07001088 return NO_ERROR;
1089}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001090
Svetoslavd85084b2014-03-20 10:28:31 -07001091status_t SurfaceFlinger::clearAnimationFrameStats() {
1092 Mutex::Autolock _l(mStateLock);
1093 mAnimFrameTracker.clearStats();
1094 return NO_ERROR;
1095}
1096
1097status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1098 Mutex::Autolock _l(mStateLock);
1099 mAnimFrameTracker.getStats(outStats);
1100 return NO_ERROR;
1101}
1102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1104 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001105 Mutex::Autolock _l(mStateLock);
1106
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001107 const auto display = getDisplayDeviceLocked(displayToken);
1108 if (!display) {
1109 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001110 return BAD_VALUE;
1111 }
1112
Peiyong Linfb069302018-04-25 14:34:31 -07001113 // At this point the DisplayDeivce should already be set up,
1114 // meaning the luminance information is already queried from
1115 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001116 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001117 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1118 capabilities.getDesiredMaxLuminance(),
1119 capabilities.getDesiredMaxAverageLuminance(),
1120 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001121
1122 return NO_ERROR;
1123}
1124
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001125status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001126 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001127 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001128
Chia-I Wu90f669f2017-10-05 14:24:41 -07001129 if (mInjectVSyncs == enable) {
1130 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001131 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001132
1133 if (enable) {
1134 ALOGV("VSync Injections enabled");
1135 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001136 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001137 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001138 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001139 impl::EventThread::InterceptVSyncsCallback(),
1140 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001141 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001142 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001143 } else {
1144 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001145 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001146 }
1147
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001148 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001149 }));
1150
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001151 return NO_ERROR;
1152}
1153
1154status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001155 Mutex::Autolock _l(mStateLock);
1156
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001157 if (!mInjectVSyncs) {
1158 ALOGE("VSync Injections not enabled");
1159 return BAD_VALUE;
1160 }
1161 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1162 ALOGV("Injecting VSync inside SurfaceFlinger");
1163 mVSyncInjector->onInjectSyncEvent(when);
1164 }
1165 return NO_ERROR;
1166}
1167
Lloyd Pique755e3192018-01-31 16:46:15 -08001168status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1169 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001170 IPCThreadState* ipc = IPCThreadState::self();
1171 const int pid = ipc->getCallingPid();
1172 const int uid = ipc->getCallingUid();
1173 if ((uid != AID_SHELL) &&
1174 !PermissionCache::checkPermission(sDump, pid, uid)) {
1175 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1176 return PERMISSION_DENIED;
1177 }
1178
1179 // Try to acquire a lock for 1s, fail gracefully
1180 const status_t err = mStateLock.timedLock(s2ns(1));
1181 const bool locked = (err == NO_ERROR);
1182 if (!locked) {
1183 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1184 return TIMED_OUT;
1185 }
1186
1187 outLayers->clear();
1188 mCurrentState.traverseInZOrder([&](Layer* layer) {
1189 outLayers->push_back(layer->getLayerDebugInfo());
1190 });
1191
1192 mStateLock.unlock();
1193 return NO_ERROR;
1194}
1195
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001196// ----------------------------------------------------------------------------
1197
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001198sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1199 ISurfaceComposer::VsyncSource vsyncSource) {
1200 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1201 return mSFEventThread->createEventConnection();
1202 } else {
1203 return mEventThread->createEventConnection();
1204 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001205}
1206
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001207// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001208
1209void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001210 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001211}
1212
1213void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001214 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001215}
1216
1217void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001218 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001219}
1220
1221void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001222 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001223 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001224}
1225
1226status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001227 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001228 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229}
1230
1231status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001232 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001233 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234 if (res == NO_ERROR) {
1235 msg->wait();
1236 }
1237 return res;
1238}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001239
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001240void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001241 do {
1242 waitForEvent();
1243 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001244}
1245
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246void SurfaceFlinger::enableHardwareVsync() {
1247 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001248 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001249 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001250 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001252 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001253}
1254
Jesse Hall948fe0c2013-10-14 12:56:09 -07001255void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256 Mutex::Autolock _l(mHWVsyncLock);
1257
Jesse Hall948fe0c2013-10-14 12:56:09 -07001258 if (makeAvailable) {
1259 mHWVsyncAvailable = true;
1260 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001261 // Hardware vsync is not currently available, so abort the resync
1262 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001263 return;
1264 }
1265
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001266 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1267 if (!getHwComposer().isConnected(displayId)) {
1268 return;
1269 }
1270
1271 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001272 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273
1274 mPrimaryDispSync.reset();
1275 mPrimaryDispSync.setPeriod(period);
1276
1277 if (!mPrimaryHWVsyncEnabled) {
1278 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001279 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001280 mPrimaryHWVsyncEnabled = true;
1281 }
1282}
1283
Jesse Hall948fe0c2013-10-14 12:56:09 -07001284void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001285 Mutex::Autolock _l(mHWVsyncLock);
1286 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001287 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288 mPrimaryDispSync.endResync();
1289 mPrimaryHWVsyncEnabled = false;
1290 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001291 if (makeUnavailable) {
1292 mHWVsyncAvailable = false;
1293 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294}
1295
Tim Murray4a4e4a22016-04-19 16:29:23 +00001296void SurfaceFlinger::resyncWithRateLimit() {
1297 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001298
1299 // No explicit locking is needed here since EventThread holds a lock while calling this method
1300 static nsecs_t sLastResyncAttempted = 0;
1301 const nsecs_t now = systemTime();
1302 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001303 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001304 }
Dan Stoza57164302017-05-08 14:03:54 -07001305 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001306}
1307
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001308void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1309 int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001310 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001311 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001312 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001313 return;
1314 }
1315
1316 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001317 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001318 return;
1319 }
1320
Jamie Gennisd1700752013-10-14 12:22:52 -07001321 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001322
Jamie Gennisd1700752013-10-14 12:22:52 -07001323 { // Scope for the lock
1324 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001325 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001326 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001327 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001328 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001329
1330 if (needsHwVsync) {
1331 enableHardwareVsync();
1332 } else {
1333 disableHardwareVsync(false);
1334 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001335}
1336
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001337void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001338 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1339 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001340}
1341
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001342void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001343 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001344 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001345 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001346
Lloyd Piqueba04e622017-12-14 17:11:26 -08001347 // Ignore events that do not have the right sequenceId.
1348 if (sequenceId != getBE().mComposerSequenceId) {
1349 return;
1350 }
1351
Steven Thomasb02664d2017-07-26 18:48:28 -07001352 // Only lock if we're not on the main thread. This function is normally
1353 // called on a hwbinder thread, but for the primary display it's called on
1354 // the main thread with the state lock already held, so don't attempt to
1355 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001356 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001357
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001358 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001359
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001360 if (std::this_thread::get_id() == mMainThreadId) {
1361 // Process all pending hot plug events immediately if we are on the main thread.
1362 processDisplayHotplugEventsLocked();
1363 }
1364
Lloyd Piqueba04e622017-12-14 17:11:26 -08001365 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001366}
1367
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001368void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001369 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001370 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001372 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001373 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001374}
1375
Dan Stoza9e56aa02015-11-02 13:00:03 -08001376void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001377 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001379 getHwComposer().setVsyncEnabled(disp,
1380 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001381}
1382
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001383// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001384void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001385 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001386 // Clear the drawing state so that the logic inside of
1387 // handleTransactionLocked will fire. It will determine the delta between
1388 // mCurrentState and mDrawingState and re-apply all changes when we make the
1389 // transition.
1390 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001391 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001392 mDisplays.clear();
1393}
1394
Steven Thomas050b2c82017-03-06 11:45:16 -08001395void SurfaceFlinger::updateVrFlinger() {
1396 if (!mVrFlinger)
1397 return;
1398 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001399 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001400 return;
1401 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402
David Sodman105b7dc2017-11-04 20:28:14 -07001403 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001404 ALOGE("Vr flinger is only supported for remote hardware composer"
1405 " service connections. Ignoring request to transition to vr"
1406 " flinger.");
1407 mVrFlingerRequestsDisplay = false;
1408 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001409 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001410
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001411 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001412
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001413 const auto display = getDefaultDisplayDeviceLocked();
1414 LOG_ALWAYS_FATAL_IF(!display);
1415 const int currentDisplayPowerMode = display->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416
Steven Thomasb02664d2017-07-26 18:48:28 -07001417 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001418 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001420
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001422 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001423 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1424 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001425 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001426
David Sodman105b7dc2017-11-04 20:28:14 -07001427 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1428 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001429
1430 if (vrFlingerRequestsDisplay) {
1431 mVrFlinger->GrantDisplayOwnership();
1432 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001433 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001434 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001435
1436 mVisibleRegionsDirty = true;
1437 invalidateHwcGeometry();
1438
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001439 // Re-enable default display.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001440 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001441
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001443 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 const nsecs_t period = activeConfig->getVsyncPeriod();
1445 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001446
Steven Thomasb02664d2017-07-26 18:48:28 -07001447 // Use phase of 0 since phase is not known.
1448 // Use latency of 0, which will snap to the ideal latency.
1449 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001450
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001451 android_atomic_or(1, &mRepaintEverything);
1452 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001453}
1454
Mathias Agopian4fec8732012-06-29 14:12:52 -07001455void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001456 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001457 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001458 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001459 bool frameMissed = !mHadClientComposition &&
1460 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001461 (mPreviousPresentFence->getSignalTime() ==
1462 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001463 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001464 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001465 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001466 mTimeStats.incrementMissedFrames();
1467 if (mPropagateBackpressure) {
1468 signalLayerUpdate();
1469 break;
1470 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001471 }
Dan Stoza50182882016-07-08 12:02:20 -07001472
Steven Thomas050b2c82017-03-06 11:45:16 -08001473 // Now that we're going to make it to the handleMessageTransaction()
1474 // call below it's safe to call updateVrFlinger(), which will
1475 // potentially trigger a display handoff.
1476 updateVrFlinger();
1477
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478 bool refreshNeeded = handleMessageTransaction();
1479 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001480 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001481 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001482 // Signal a refresh if a transaction modified the window state,
1483 // a new buffer was latched, or if HWC has requested a full
1484 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001485 signalRefresh();
1486 }
1487 break;
1488 }
1489 case MessageQueue::REFRESH: {
1490 handleMessageRefresh();
1491 break;
1492 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001493 }
1494}
1495
Dan Stoza6b9454d2014-11-07 16:00:59 -08001496bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001497 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001498 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001499 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001500 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001501 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001502 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001503}
1504
Dan Stoza6b9454d2014-11-07 16:00:59 -08001505bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001506 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001507 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001508}
1509
1510void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001511 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001512
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001513 mRefreshPending = false;
1514
Chia-I Wu30505fb2018-03-26 16:20:31 -07001515 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001516
Chia-I Wu30505fb2018-03-26 16:20:31 -07001517 preComposition(refreshStartTime);
1518 rebuildLayerStacks();
1519 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001520 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001521 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001522 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001523 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001524 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001525
Dan Stozabfbffeb2016-07-21 14:49:33 -07001526 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001527 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001528 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001529 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001530 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001531 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001532
Dan Stoza9e56aa02015-11-02 13:00:03 -08001533 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001534}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001535
Mathias Agopiancd60f992012-08-16 16:28:27 -07001536void SurfaceFlinger::doDebugFlashRegions()
1537{
1538 // is debugging enabled
1539 if (CC_LIKELY(!mDebugRegion))
1540 return;
1541
1542 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001543 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001544 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001546 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547 if (!dirtyRegion.isEmpty()) {
1548 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001549 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001550
1551 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001552 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001553 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001554 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1555
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001556 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001557 }
1558 }
1559 }
1560
1561 postFramebuffer();
1562
1563 if (mDebugRegion > 1) {
1564 usleep(mDebugRegion * 1000);
1565 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001566
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001567 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001568 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001569 continue;
1570 }
1571
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001572 status_t result = display->prepareFrame(*getBE().mHwc);
1573 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001574 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001575 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001576}
1577
Adrian Roos1e1a1282017-11-01 19:05:31 +01001578void SurfaceFlinger::doTracing(const char* where) {
1579 ATRACE_CALL();
1580 ATRACE_NAME(where);
1581 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001582 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001583 }
1584}
1585
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001586void SurfaceFlinger::logLayerStats() {
1587 ATRACE_CALL();
1588 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001589 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001590 if (display->isPrimary()) {
1591 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001592 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001593 }
1594 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001595
1596 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001597 }
1598}
1599
Chia-I Wu30505fb2018-03-26 16:20:31 -07001600void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001601{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001602 ATRACE_CALL();
1603 ALOGV("preComposition");
1604
Mathias Agopiancd60f992012-08-16 16:28:27 -07001605 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001606 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001607 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001608 needExtraInvalidate = true;
1609 }
Robert Carr2047fae2016-11-28 14:09:09 -08001610 });
1611
Mathias Agopiancd60f992012-08-16 16:28:27 -07001612 if (needExtraInvalidate) {
1613 signalLayerUpdate();
1614 }
1615}
1616
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001617void SurfaceFlinger::updateCompositorTiming(
1618 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1619 std::shared_ptr<FenceTime>& presentFenceTime) {
1620 // Update queue of past composite+present times and determine the
1621 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001622 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001623 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001624 while (!getBE().mCompositePresentTimes.empty()) {
1625 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001626 // Cached values should have been updated before calling this method,
1627 // which helps avoid duplicate syscalls.
1628 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1629 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1630 break;
1631 }
1632 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001633 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001634 }
1635
1636 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001637 while (getBE().mCompositePresentTimes.size() > 16) {
1638 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001639 }
1640
Brian Andersond0010582017-03-07 13:20:31 -08001641 setCompositorTimingSnapped(
1642 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1643}
1644
1645void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1646 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001647 // Integer division and modulo round toward 0 not -inf, so we need to
1648 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001649 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1651 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1652
Brian Andersond0010582017-03-07 13:20:31 -08001653 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1654 if (idealLatency <= 0) {
1655 idealLatency = vsyncInterval;
1656 }
1657
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001658 // Snap the latency to a value that removes scheduling jitter from the
1659 // composition and present times, which often have >1ms of jitter.
1660 // Reducing jitter is important if an app attempts to extrapolate
1661 // something (such as user input) to an accurate diasplay time.
1662 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1663 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001664 nsecs_t bias = vsyncInterval / 2;
1665 int64_t extraVsyncs =
1666 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1667 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1668 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001669
David Sodman99974d22017-11-28 12:04:33 -08001670 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1671 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1672 getBE().mCompositorTiming.interval = vsyncInterval;
1673 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001674}
1675
Chia-I Wu30505fb2018-03-26 16:20:31 -07001676void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001677{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001678 ATRACE_CALL();
1679 ALOGV("postComposition");
1680
Brian Anderson3546a3f2016-07-14 11:51:14 -07001681 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001682 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001683 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001684 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001685 }
1686
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001687 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001688 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001689
David Sodman73beded2017-11-15 11:56:06 -08001690 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001691 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001692 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001693 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001694 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001695 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001696 } else {
1697 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1698 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001699
David Sodman73beded2017-11-15 11:56:06 -08001700 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001701 mPreviousPresentFence =
1702 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1703 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001704 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001705
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001706 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1707 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1708
Chia-I Wu30505fb2018-03-26 16:20:31 -07001709 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001710 // when we started doing work for this frame, but that should be okay
1711 // since updateCompositorTiming has snapping logic.
1712 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001713 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001714 CompositorTiming compositorTiming;
1715 {
David Sodman99974d22017-11-28 12:04:33 -08001716 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1717 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001718 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001719
Robert Carr2047fae2016-11-28 14:09:09 -08001720 mDrawingState.traverseInZOrder([&](Layer* layer) {
1721 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001722 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001723 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001724 recordBufferingStats(layer->getName().string(),
1725 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001726 }
Robert Carr2047fae2016-11-28 14:09:09 -08001727 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001728
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001729 if (presentFenceTime->isValid()) {
1730 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001731 enableHardwareVsync();
1732 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001733 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001734 }
1735 }
1736
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001737 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001738 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001739 enableHardwareVsync();
1740 }
1741 }
1742
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001743 if (mAnimCompositionPending) {
1744 mAnimCompositionPending = false;
1745
Brian Anderson4e606e32017-03-16 15:34:57 -07001746 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001747 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001748 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001749 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001750 // The HWC doesn't support present fences, so use the refresh
1751 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001752 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001753 mAnimFrameTracker.setActualPresentTime(presentTime);
1754 }
1755 mAnimFrameTracker.advanceFrame();
1756 }
Dan Stozab90cf072015-03-05 11:05:59 -08001757
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001758 mTimeStats.incrementTotalFrames();
1759 if (mHadClientComposition) {
1760 mTimeStats.incrementClientCompositionFrames();
1761 }
1762
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001763 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001764 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001765 return;
1766 }
1767
1768 nsecs_t currentTime = systemTime();
1769 if (mHasPoweredOff) {
1770 mHasPoweredOff = false;
1771 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001772 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001773 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001774 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1775 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001776 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001777 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001778 }
David Sodman4a36e932017-11-07 14:29:47 -08001779 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001780 }
David Sodman4a36e932017-11-07 14:29:47 -08001781 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001782
1783 {
1784 std::lock_guard lock(mTexturePoolMutex);
1785 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1786 if (refillCount > 0) {
1787 const size_t offset = mTexturePool.size();
1788 mTexturePool.resize(mTexturePoolSize);
1789 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1790 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1791 }
1792 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001793}
1794
1795void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001796 ATRACE_CALL();
1797 ALOGV("rebuildLayerStacks");
1798
Mathias Agopiancd60f992012-08-16 16:28:27 -07001799 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001800 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001801 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001802 mVisibleRegionsDirty = false;
1803 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001804
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001805 for (const auto& pair : mDisplays) {
1806 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001807 Region opaqueRegion;
1808 Region dirtyRegion;
1809 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001810 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001811 const Transform& tr = display->getTransform();
1812 const Rect bounds = display->getBounds();
1813 if (display->isPoweredOn()) {
1814 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001815
Jeff Sharkey76488112017-02-27 14:15:18 -07001816 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001817 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001818 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001819 Region drawRegion(tr.transform(
1820 layer->visibleNonTransparentRegion));
1821 drawRegion.andSelf(bounds);
1822 if (!drawRegion.isEmpty()) {
1823 layersSortedByZ.add(layer);
1824 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001825 // Clear out the HWC layer if this layer was
1826 // previously visible, but no longer is
Dominik Laskowski7e045462018-05-30 13:02:02 -07001827 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001828 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001829 } else {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001830 // WM changes display->layerStack upon sleep/awake.
Chia-I Wu30505fb2018-03-26 16:20:31 -07001831 // Here we make sure we delete the HWC layers even if
1832 // WM changed their layer stack.
Dominik Laskowski7e045462018-05-30 13:02:02 -07001833 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001834 }
1835
1836 // If a layer is not going to get a release fence because
1837 // it is invisible, but it is also going to release its
1838 // old buffer, add it to the list of layers needing
1839 // fences.
1840 if (hwcLayerDestroyed) {
1841 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1842 mLayersWithQueuedFrames.cend(), layer);
1843 if (found != mLayersWithQueuedFrames.cend()) {
1844 layersNeedingFences.add(layer);
1845 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001846 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001847 });
1848 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001849 display->setVisibleLayersSortedByZ(layersSortedByZ);
1850 display->setLayersNeedingFences(layersNeedingFences);
1851 display->undefinedRegion.set(bounds);
1852 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1853 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001854 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001855 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001856}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001857
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001858// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001859// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001860// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001861// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001862// The returned HDR data space is one of
1863// - Dataspace::UNKNOWN
1864// - Dataspace::BT2020_HLG
1865// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001866Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1867 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001868 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001869 *outHdrDataSpace = Dataspace::UNKNOWN;
1870
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001871 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001872 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001873 case Dataspace::V0_SCRGB:
1874 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001875 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001876 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001877 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001878 case Dataspace::BT2020_PQ:
1879 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001880 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001881 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001882 case Dataspace::BT2020_HLG:
1883 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001884 // When there's mixed PQ content and HLG content, we set the HDR
1885 // data space to be BT2020_PQ and convert HLG to PQ.
1886 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1887 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001888 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001889 break;
1890 default:
1891 break;
1892 }
Romain Guy54f154a2017-10-24 21:40:32 +01001893 }
1894
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001895 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001896}
1897
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001898// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001899void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1900 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001901 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1902 *outMode = ColorMode::NATIVE;
1903 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001904 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001905 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001906 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001907
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001908 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001909 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001910
Peiyong Lindfde5112018-06-05 10:58:41 -07001911 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001912 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001913 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001914 if (isHdr) {
1915 bestDataSpace = hdrDataSpace;
1916 }
1917
Chia-I Wu0d711262018-05-21 15:19:35 -07001918 RenderIntent intent;
1919 switch (mDisplayColorSetting) {
1920 case DisplayColorSetting::MANAGED:
1921 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001922 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001923 break;
1924 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001925 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001926 break;
1927 default: // vendor display color setting
1928 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1929 break;
1930 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001931
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001932 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001933}
1934
Chia-I Wu30505fb2018-03-26 16:20:31 -07001935void SurfaceFlinger::setUpHWComposer() {
1936 ATRACE_CALL();
1937 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001939 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001940 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
1941 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1942 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07001943
1944 // If nothing has changed (!dirty), don't recompose.
1945 // If something changed, but we don't currently have any visible layers,
1946 // and didn't when we last did a composition, then skip it this time.
1947 // The second rule does two things:
1948 // - When all layers are removed from a display, we'll emit one black
1949 // frame, then nothing more until we get new layers.
1950 // - When a display is created with a private layer stack, we won't
1951 // emit any black frames until a layer is added to the layer stack.
1952 bool mustRecompose = dirty && !(empty && wasEmpty);
1953
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001954 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001955 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
1956 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07001957
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001958 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001959
1960 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001961 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07001962 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001963 }
1964
Chia-I Wu30505fb2018-03-26 16:20:31 -07001965 // build the h/w work list
1966 if (CC_UNLIKELY(mGeometryInvalid)) {
1967 mGeometryInvalid = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001968 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001969 const auto displayId = display->getId();
1970 if (displayId >= 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001971 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001972 for (size_t i = 0; i < currentLayers.size(); i++) {
1973 const auto& layer = currentLayers[i];
Dominik Laskowski7e045462018-05-30 13:02:02 -07001974 if (!layer->hasHwcLayer(displayId)) {
1975 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1976 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001977 continue;
1978 }
1979 }
1980
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001981 layer->setGeometry(display, i);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001982 if (mDebugDisableHWC || mDebugRegion) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001983 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001984 }
1985 }
1986 }
1987 }
1988 }
1989
Chia-I Wu30505fb2018-03-26 16:20:31 -07001990 // Set the per-frame data
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001991 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001992 const auto displayId = display->getId();
1993 if (displayId < 0) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001994 continue;
1995 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07001996
Chia-I Wu28f320b2018-05-03 11:02:56 -07001997 if (mDrawingState.colorMatrixChanged) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001998 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski7e045462018-05-30 13:02:02 -07001999 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002000 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002001 displayId, result);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002002 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002003 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu692e0832018-06-05 15:46:58 -07002004 if (layer->isHdrY410()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002005 layer->forceClientComposition(displayId);
Chia-I Wu692e0832018-06-05 15:46:58 -07002006 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2007 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
2008 !display->hasHDR10Support()) {
2009 layer->forceClientComposition(displayId);
2010 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2011 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2012 !display->hasHLGSupport()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002013 layer->forceClientComposition(displayId);
Peiyong Linf59a7192018-04-25 11:19:31 -07002014 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002015
Dominik Laskowski7e045462018-05-30 13:02:02 -07002016 if (layer->getForceClientComposition(displayId)) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002017 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002018 layer->setCompositionType(displayId, HWC2::Composition::Client);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002019 continue;
2020 }
2021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002022 layer->setPerFrameData(display);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002023 }
2024
2025 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002026 ColorMode colorMode;
2027 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002028 RenderIntent renderIntent;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002029 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
2030 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002031 }
2032 }
2033
Chia-I Wu28f320b2018-05-03 11:02:56 -07002034 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07002035
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002036 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002037 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002038 continue;
2039 }
2040
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002041 status_t result = display->prepareFrame(*getBE().mHwc);
2042 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002043 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002044 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002045}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002046
Mathias Agopiancd60f992012-08-16 16:28:27 -07002047void SurfaceFlinger::doComposition() {
2048 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002049 ALOGV("doComposition");
2050
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002051 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002052 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002053 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002054 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002055 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002056
2057 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002058 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002059
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002060 display->dirtyRegion.clear();
2061 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002062 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002063 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002064 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002065}
2066
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002067void SurfaceFlinger::postFramebuffer()
2068{
Mathias Agopian841cde52012-03-01 15:44:37 -08002069 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002070 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002071
Mathias Agopiana44b0412011-10-16 18:46:35 -07002072 const nsecs_t now = systemTime();
2073 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002074
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002075 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002076 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002077 continue;
2078 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002079 const auto displayId = display->getId();
2080 if (displayId >= 0) {
2081 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002082 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002083 display->onSwapBuffersCompleted();
2084 display->makeCurrent();
2085 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002086 // The layer buffer from the previous frame (if any) is released
2087 // by HWC only when the release fence from this frame (if any) is
2088 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002089 auto hwcLayer = layer->getHwcLayer(displayId);
2090 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002091
2092 // If the layer was client composited in the previous frame, we
2093 // need to merge with the previous client target acquire fence.
2094 // Since we do not track that, always merge with the current
2095 // client target acquire fence when it is available, even though
2096 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002097 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002098 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002099 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002100 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002101
David Sodmanb8af7922017-12-21 15:17:55 -08002102 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002103 }
Chia-I Wu83806892017-11-16 10:50:20 -08002104
2105 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002106 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002107 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002108 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002109 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002110 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002111 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002112 }
2113 }
2114
Dominik Laskowski7e045462018-05-30 13:02:02 -07002115 if (displayId >= 0) {
2116 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002117 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002118 }
2119
Mathias Agopiana44b0412011-10-16 18:46:35 -07002120 mLastSwapBufferTime = systemTime() - now;
2121 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002122
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002123 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002124 const auto display = getDefaultDisplayDeviceLocked();
2125 if (display && getHwComposer().isConnected(display->getId())) {
2126 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002127 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2128 logFrameStats();
2129 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002130 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131}
2132
Mathias Agopian87baae12012-07-31 12:38:26 -07002133void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002134{
Mathias Agopian841cde52012-03-01 15:44:37 -08002135 ATRACE_CALL();
2136
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002137 // here we keep a copy of the drawing state (that is the state that's
2138 // going to be overwritten by handleTransactionLocked()) outside of
2139 // mStateLock so that the side-effects of the State assignment
2140 // don't happen with mStateLock held (which can cause deadlocks).
2141 State drawingState(mDrawingState);
2142
Mathias Agopianca4d3602011-05-19 15:38:14 -07002143 Mutex::Autolock _l(mStateLock);
2144 const nsecs_t now = systemTime();
2145 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002146
Mathias Agopianca4d3602011-05-19 15:38:14 -07002147 // Here we're guaranteed that some transaction flags are set
2148 // so we can call handleTransactionLocked() unconditionally.
2149 // We call getTransactionFlags(), which will also clear the flags,
2150 // with mStateLock held to guarantee that mCurrentState won't change
2151 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002152
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002153 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002154 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002155 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002156
Mathias Agopianca4d3602011-05-19 15:38:14 -07002157 mLastTransactionTime = systemTime() - now;
2158 mDebugInTransaction = 0;
2159 invalidateHwcGeometry();
2160 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002161}
2162
Dominik Laskowski7e045462018-05-30 13:02:02 -07002163DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002164 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002165 // Figure out whether the event is for the primary display or an
2166 // external display by matching the Hwc display id against one for a
2167 // connected display. If we did not find a match, we then check what
2168 // displays are not already connected to determine the type. If we don't
2169 // have a connected primary display, we assume the new display is meant to
2170 // be the primary display, and then if we don't have an external display,
2171 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002172 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2173 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002174 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002175 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002176 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002177 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002178 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002179 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002180 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002181 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002182 return DisplayDevice::DISPLAY_EXTERNAL;
2183 }
2184
2185 return DisplayDevice::DISPLAY_ID_INVALID;
2186}
2187
Lloyd Piqueba04e622017-12-14 17:11:26 -08002188void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2189 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002190 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002191 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002192 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002193 continue;
2194 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002195
2196 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2197 ALOGE("External displays are not supported by the vr hardware composer.");
2198 continue;
2199 }
2200
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002201 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002202 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002203 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002204 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002205 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002206
2207 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002208 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002209 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002210 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002211 DisplayDeviceState info;
2212 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002213 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2214 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002215 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002216 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002217 mInterceptor->saveDisplayCreation(info);
2218 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002219 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002220 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002221
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002222 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002223 if (idx >= 0) {
2224 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002225 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002226 mCurrentState.displays.removeItemsAt(idx);
2227 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002228 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002229 }
2230
2231 processDisplayChangesLocked();
2232 }
2233
2234 mPendingHotplugEvents.clear();
2235}
2236
Lloyd Pique99d3da52018-01-22 17:48:03 -08002237sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002238 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002239 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002240 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002241 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002242
Lloyd Pique99d3da52018-01-22 17:48:03 -08002243 if (hasWideColorDisplay) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002244 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002245 for (ColorMode colorMode : modes) {
2246 switch (colorMode) {
2247 case ColorMode::DISPLAY_P3:
2248 case ColorMode::ADOBE_RGB:
2249 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002250 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002251 break;
2252 default:
2253 break;
2254 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002255
Dominik Laskowski7e045462018-05-30 13:02:02 -07002256 std::vector<RenderIntent> renderIntents =
2257 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002258 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002259 }
2260 }
2261
Peiyong Lin62665892018-04-16 11:07:44 -07002262 HdrCapabilities hdrCapabilities;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002263 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002264
2265 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2266 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2267
2268 /*
2269 * Create our display's surface
2270 */
2271 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2272 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002273 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002274 renderSurface->setNativeWindow(nativeWindow.get());
2275 const int displayWidth = renderSurface->queryWidth();
2276 const int displayHeight = renderSurface->queryHeight();
2277
2278 // Make sure that composition can never be stalled by a virtual display
2279 // consumer that isn't processing buffers fast enough. We have to do this
2280 // in two places:
2281 // * Here, in case the display is composed entirely by HWC.
2282 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2283 // window's swap interval in eglMakeCurrent, so they'll override the
2284 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002285 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002286 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2287 }
2288
2289 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002290 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002291
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002292 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002293 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2294 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2295 displayHeight, hasWideColorGamut, hdrCapabilities,
2296 getHwComposer().getSupportedPerFrameMetadata(displayId),
2297 hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002298
2299 if (maxFrameBufferAcquiredBuffers >= 3) {
2300 nativeWindowSurface->preallocateBuffers();
2301 }
2302
2303 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002304 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2305 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002306 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002307 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002308 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002309 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002310 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002311 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002312 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002313 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002314 display->setLayerStack(state.layerStack);
2315 display->setProjection(state.orientation, state.viewport, state.frame);
2316 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002317
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002318 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002319}
2320
Lloyd Pique347200f2017-12-14 17:00:15 -08002321void SurfaceFlinger::processDisplayChangesLocked() {
2322 // here we take advantage of Vector's copy-on-write semantics to
2323 // improve performance by skipping the transaction entirely when
2324 // know that the lists are identical
2325 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2326 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2327 if (!curr.isIdenticalTo(draw)) {
2328 mVisibleRegionsDirty = true;
2329 const size_t cc = curr.size();
2330 size_t dc = draw.size();
2331
2332 // find the displays that were removed
2333 // (ie: in drawing state but not in current state)
2334 // also handle displays that changed
2335 // (ie: displays that are in both lists)
2336 for (size_t i = 0; i < dc;) {
2337 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2338 if (j < 0) {
2339 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002340 // Call makeCurrent() on the primary display so we can
2341 // be sure that nothing associated with this display
2342 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002343 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2344 defaultDisplay->makeCurrent();
2345 }
2346 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2347 display->disconnect(getHwComposer());
2348 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002349 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2350 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2351 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2352 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2353 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002354 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002355 } else {
2356 // this display is in both lists. see if something changed.
2357 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002358 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002359 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2360 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2361 if (state_binder != draw_binder) {
2362 // changing the surface is like destroying and
2363 // recreating the DisplayDevice, so we just remove it
2364 // from the drawing state, so that it get re-added
2365 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002366 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2367 display->disconnect(getHwComposer());
2368 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002369 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002370 mDrawingState.displays.removeItemsAt(i);
2371 dc--;
2372 // at this point we must loop to the next item
2373 continue;
2374 }
2375
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002376 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002377 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002378 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002379 }
2380 if ((state.orientation != draw[i].orientation) ||
2381 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002382 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002383 }
2384 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002385 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002386 }
2387 }
2388 }
2389 ++i;
2390 }
2391
2392 // find displays that were added
2393 // (ie: in current state but not in drawing state)
2394 for (size_t i = 0; i < cc; i++) {
2395 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2396 const DisplayDeviceState& state(curr[i]);
2397
2398 sp<DisplaySurface> dispSurface;
2399 sp<IGraphicBufferProducer> producer;
2400 sp<IGraphicBufferProducer> bqProducer;
2401 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002402 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002403
Dominik Laskowski7e045462018-05-30 13:02:02 -07002404 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002405 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002406 // Virtual displays without a surface are dormant:
2407 // they have external state (layer stack, projection,
2408 // etc.) but no internal state (i.e. a DisplayDevice).
2409 if (state.surface != nullptr) {
2410 // Allow VR composer to use virtual displays.
2411 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2412 int width = 0;
2413 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2414 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2415 int height = 0;
2416 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2417 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2418 int intFormat = 0;
2419 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2420 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002421 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002422
Dominik Laskowski7e045462018-05-30 13:02:02 -07002423 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2424 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002425 }
2426
2427 // TODO: Plumb requested format back up to consumer
2428
2429 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002430 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002431 bqProducer, bqConsumer,
2432 state.displayName);
2433
2434 dispSurface = vds;
2435 producer = vds;
2436 }
2437 } else {
2438 ALOGE_IF(state.surface != nullptr,
2439 "adding a supported display, but rendering "
2440 "surface is provided (%p), ignoring it",
2441 state.surface.get());
2442
Dominik Laskowski7e045462018-05-30 13:02:02 -07002443 displayId = state.type;
2444 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002445 producer = bqProducer;
2446 }
2447
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002448 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002449 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002450 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002451 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002452 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002453 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002454 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2455 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2456 true);
2457 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2458 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2459 true);
2460 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002461 }
2462 }
2463 }
2464 }
2465 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002466
2467 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002468}
2469
Mathias Agopian87baae12012-07-31 12:38:26 -07002470void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002471{
Dan Stoza7dde5992015-05-22 09:51:44 -07002472 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002473 mCurrentState.traverseInZOrder([](Layer* layer) {
2474 layer->notifyAvailableFrames();
2475 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002476
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002477 /*
2478 * Traversal of the children
2479 * (perform the transaction for each of them if needed)
2480 */
2481
Mathias Agopian3559b072012-08-15 13:46:03 -07002482 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002483 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002485 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486
2487 const uint32_t flags = layer->doTransaction(0);
2488 if (flags & Layer::eVisibleRegion)
2489 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002490 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491 }
2492
2493 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002494 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495 */
2496
Mathias Agopiane57f2922012-08-09 16:29:12 -07002497 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002498 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002499 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002500 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002502 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002503 // The transform hint might have changed for some layers
2504 // (either because a display has changed, or because a layer
2505 // as changed).
2506 //
2507 // Walk through all the layers in currentLayers,
2508 // and update their transform hint.
2509 //
2510 // If a layer is visible only on a single display, then that
2511 // display is used to calculate the hint, otherwise we use the
2512 // default display.
2513 //
2514 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2515 // the hint is set before we acquire a buffer from the surface texture.
2516 //
2517 // NOTE: layer transactions have taken place already, so we use their
2518 // drawing state. However, SurfaceFlinger's own transaction has not
2519 // happened yet, so we must use the current state layer list
2520 // (soon to become the drawing state list).
2521 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002522 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002523 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002524 bool first = true;
2525 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002526 // NOTE: we rely on the fact that layers are sorted by
2527 // layerStack first (so we don't have to traverse the list
2528 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002529 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002530 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002531 currentlayerStack = layerStack;
2532 // figure out if this layerstack is mirrored
2533 // (more than one display) if so, pick the default display,
2534 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002535 hintDisplay = nullptr;
2536 for (const auto& [token, display] : mDisplays) {
2537 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2538 if (hintDisplay) {
2539 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002540 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002541 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002542 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002543 }
2544 }
2545 }
2546 }
Chet Haase91d25932013-04-11 15:24:55 -07002547
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002548 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002549 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2550 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002551
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002552 // could be null when this layer is using a layerStack
2553 // that is not visible on any display. Also can occur at
2554 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002555 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002556 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002557
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002558 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002559 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002560 if (hintDisplay) {
2561 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002562 }
Robert Carr2047fae2016-11-28 14:09:09 -08002563
2564 first = false;
2565 });
Mathias Agopian84300952012-11-21 16:02:13 -08002566 }
2567
2568
Mathias Agopian3559b072012-08-15 13:46:03 -07002569 /*
2570 * Perform our own transaction if needed
2571 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002572
2573 if (mLayersAdded) {
2574 mLayersAdded = false;
2575 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002576 mVisibleRegionsDirty = true;
2577 }
2578
2579 // some layers might have been removed, so
2580 // we need to update the regions they're exposing.
2581 if (mLayersRemoved) {
2582 mLayersRemoved = false;
2583 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002584 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002585 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002586 // this layer is not visible anymore
2587 // TODO: we could traverse the tree from front to back and
2588 // compute the actual visible region
2589 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002590 Region visibleReg;
2591 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002592 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002593 }
Robert Carr2047fae2016-11-28 14:09:09 -08002594 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595 }
2596
2597 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002598
2599 updateCursorAsync();
2600}
2601
2602void SurfaceFlinger::updateCursorAsync()
2603{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002604 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002605 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002606 continue;
2607 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002608
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002609 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2610 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002611 }
2612 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002613}
2614
2615void SurfaceFlinger::commitTransaction()
2616{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002617 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002618 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002619 for (const auto& l : mLayersPendingRemoval) {
2620 recordBufferingStats(l->getName().string(),
2621 l->getOccupancyHistory(true));
2622 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002623 }
2624 mLayersPendingRemoval.clear();
2625 }
2626
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002627 // If this transaction is part of a window animation then the next frame
2628 // we composite should be considered an animation as well.
2629 mAnimCompositionPending = mAnimTransactionPending;
2630
Mathias Agopian4fec8732012-06-29 14:12:52 -07002631 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002632 // clear the "changed" flags in current state
2633 mCurrentState.colorMatrixChanged = false;
2634
Robert Carr1f0a16a2016-10-24 16:27:39 -07002635 mDrawingState.traverseInZOrder([](Layer* layer) {
2636 layer->commitChildList();
2637 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002638 mTransactionPending = false;
2639 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002640 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002641}
2642
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002643void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2644 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002645 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002646 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002647
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648 Region aboveOpaqueLayers;
2649 Region aboveCoveredLayers;
2650 Region dirty;
2651
Mathias Agopian87baae12012-07-31 12:38:26 -07002652 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653
Robert Carr2047fae2016-11-28 14:09:09 -08002654 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002655 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002656 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657
Jesse Hall01e29052013-02-19 16:13:35 -08002658 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002659 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002660 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002661 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002662
Mathias Agopianab028732010-03-16 16:41:46 -07002663 /*
2664 * opaqueRegion: area of a surface that is fully opaque.
2665 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002667
2668 /*
2669 * visibleRegion: area of a surface that is visible on screen
2670 * and not fully transparent. This is essentially the layer's
2671 * footprint minus the opaque regions above it.
2672 * Areas covered by a translucent surface are considered visible.
2673 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002674 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002675
2676 /*
2677 * coveredRegion: area of a surface that is covered by all
2678 * visible regions above it (which includes the translucent areas).
2679 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002681
Jesse Halla8026d22012-09-25 13:25:04 -07002682 /*
2683 * transparentRegion: area of a surface that is hinted to be completely
2684 * transparent. This is only used to tell when the layer has no visible
2685 * non-transparent regions and can be removed from the layer list. It
2686 * does not affect the visibleRegion of this layer or any layers
2687 * beneath it. The hint may not be correct if apps don't respect the
2688 * SurfaceView restrictions (which, sadly, some don't).
2689 */
2690 Region transparentRegion;
2691
Mathias Agopianab028732010-03-16 16:41:46 -07002692
2693 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002694 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002695 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002696 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002697 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002698 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002699 if (!visibleRegion.isEmpty()) {
2700 // Remove the transparent area from the visible region
2701 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002702 if (tr.preserveRects()) {
2703 // transform the transparent region
2704 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002705 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002706 // transformation too complex, can't do the
2707 // transparent region optimization.
2708 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002709 }
Mathias Agopianab028732010-03-16 16:41:46 -07002710 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002711
Mathias Agopianab028732010-03-16 16:41:46 -07002712 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002713 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002714 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002715 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2716 // the opaque region is the layer's footprint
2717 opaqueRegion = visibleRegion;
2718 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719 }
2720 }
2721
Robert Carre5f4f692018-01-12 13:12:28 -08002722 if (visibleRegion.isEmpty()) {
2723 layer->clearVisibilityRegions();
2724 return;
2725 }
2726
Mathias Agopianab028732010-03-16 16:41:46 -07002727 // Clip the covered region to the visible region
2728 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2729
2730 // Update aboveCoveredLayers for next (lower) layer
2731 aboveCoveredLayers.orSelf(visibleRegion);
2732
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733 // subtract the opaque region covered by the layers above us
2734 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735
2736 // compute this layer's dirty region
2737 if (layer->contentDirty) {
2738 // we need to invalidate the whole region
2739 dirty = visibleRegion;
2740 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002741 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742 layer->contentDirty = false;
2743 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002744 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002745 * the exposed region consists of two components:
2746 * 1) what's VISIBLE now and was COVERED before
2747 * 2) what's EXPOSED now less what was EXPOSED before
2748 *
2749 * note that (1) is conservative, we start with the whole
2750 * visible region but only keep what used to be covered by
2751 * something -- which mean it may have been exposed.
2752 *
2753 * (2) handles areas that were not covered by anything but got
2754 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002755 */
Mathias Agopianab028732010-03-16 16:41:46 -07002756 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002757 const Region oldVisibleRegion = layer->visibleRegion;
2758 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002759 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2760 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761 }
2762 dirty.subtractSelf(aboveOpaqueLayers);
2763
2764 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002765 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766
Mathias Agopianab028732010-03-16 16:41:46 -07002767 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002769
Jesse Halla8026d22012-09-25 13:25:04 -07002770 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771 layer->setVisibleRegion(visibleRegion);
2772 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002773 layer->setVisibleNonTransparentRegion(
2774 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002775 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776
Mathias Agopian87baae12012-07-31 12:38:26 -07002777 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778}
2779
Chia-I Wuab0c3192017-08-01 11:29:00 -07002780void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002781 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002782 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2783 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002784 }
2785 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002786}
2787
Dan Stoza6b9454d2014-11-07 16:00:59 -08002788bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002789{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002790 ALOGV("handlePageFlip");
2791
Brian Andersond6927fb2016-07-23 23:37:30 -07002792 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793
Mathias Agopian4fec8732012-06-29 14:12:52 -07002794 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002795 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002796 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002797
2798 // Store the set of layers that need updates. This set must not change as
2799 // buffers are being latched, as this could result in a deadlock.
2800 // Example: Two producers share the same command stream and:
2801 // 1.) Layer 0 is latched
2802 // 2.) Layer 0 gets a new frame
2803 // 2.) Layer 1 gets a new frame
2804 // 3.) Layer 1 is latched.
2805 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2806 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002807 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002808 if (layer->hasQueuedFrame()) {
2809 frameQueued = true;
2810 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002811 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002812 } else {
2813 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002814 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002815 } else {
2816 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002817 }
Robert Carr2047fae2016-11-28 14:09:09 -08002818 });
2819
Dan Stoza9e56aa02015-11-02 13:00:03 -08002820 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002821 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002822 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002823 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002824 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002825 newDataLatched = true;
2826 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002827 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002828
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002829 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002830
2831 // If we will need to wake up at some time in the future to deal with a
2832 // queued frame that shouldn't be displayed during this vsync period, wake
2833 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002834 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002835 signalLayerUpdate();
2836 }
2837
2838 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002839 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840}
2841
Mathias Agopianad456f92011-01-13 17:53:01 -08002842void SurfaceFlinger::invalidateHwcGeometry()
2843{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002844 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002845}
2846
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002847void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2848 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002849 // We only need to actually compose the display if:
2850 // 1) It is being handled by hardware composer, which may need this to
2851 // keep its virtual display state machine in sync, or
2852 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002853 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002854 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002855 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002856 return;
2857 }
2858
Dan Stoza9e56aa02015-11-02 13:00:03 -08002859 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002860 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002861
2862 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002863 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864}
2865
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002866bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002867 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002868
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002869 const Region bounds(display->bounds());
2870 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002871 const auto displayId = display->getId();
2872 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002873 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002874
Chia-I Wu8e50e692018-05-04 10:12:37 -07002875 bool applyColorMatrix = false;
Peiyong Lin00f9c022018-05-09 15:35:33 -07002876 bool needsLegacyColorMatrix = false;
2877 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002878
Dan Stoza9e56aa02015-11-02 13:00:03 -08002879 if (hasClientComposition) {
2880 ALOGV("hasClientComposition");
2881
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002882 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002883 if (display->hasWideColorGamut()) {
2884 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002885 }
2886 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002887 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002888 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002889
Dominik Laskowski7e045462018-05-30 13:02:02 -07002890 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002891 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2892 HWC2::Capability::SkipClientColorTransform);
2893
2894 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2895 if (applyColorMatrix) {
Peiyong Lin00f9c022018-05-09 15:35:33 -07002896 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002897 }
2898
Chia-I Wubbb44462018-05-21 15:33:27 -07002899 needsLegacyColorMatrix =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002900 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2901 outputDataspace != Dataspace::UNKNOWN && outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002902
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002903 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002904 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002905 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002906 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002907
2908 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002909 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2910 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2911 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002912 }
2913 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002914 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002915
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002916 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002917 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002918 // when using overlays, we assume a fully transparent framebuffer
2919 // NOTE: we could reduce how much we need to clear, for instance
2920 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002921 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002922 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002923 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002924 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002925 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002926 // we're left with the letterbox region
2927 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002928 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002929
2930 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002931 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002932
Mathias Agopianb9494d52012-04-18 02:28:45 -07002933 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002934 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002935 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002936 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002937 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002938 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002939
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002940 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002941 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002942 // scissor on the main display. It should never be needed
2943 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002944 const Rect& bounds = display->getBounds();
2945 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002946 if (scissor != bounds) {
2947 // scissor doesn't match the screen's dimensions, so we
2948 // need to clear everything outside of it and enable
2949 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002950
Mathias Agopianf45c5102012-10-24 16:29:17 -07002951 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002952 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002953 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002954 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002955 }
2956 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002957 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002958
Mathias Agopian85d751c2012-08-29 16:59:24 -07002959 /*
2960 * and then, render the layers targeted at the framebuffer
2961 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002962
Dan Stoza9e56aa02015-11-02 13:00:03 -08002963 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002964 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002965 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002966 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002967 const Region clip(bounds.intersect(
2968 displayTransform.transform(layer->visibleRegion)));
2969 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002970 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002971 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002972 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002973 case HWC2::Composition::Cursor:
2974 case HWC2::Composition::Device:
2975 case HWC2::Composition::Sideband:
2976 case HWC2::Composition::SolidColor: {
2977 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002978 if (layer->getClearClientTarget(displayId) && !firstLayer &&
2979 layer->isOpaque(state) && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002980 // never clear the very first layer since we're
2981 // guaranteed the FB is already cleared
2982 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002983 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002984 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002985 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002986 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002987 // switch color matrices lazily
Peiyong Lin00f9c022018-05-09 15:35:33 -07002988 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
2989 if (!legacyColorMatrixApplied) {
2990 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
2991 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002992 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07002993 } else if (legacyColorMatrixApplied) {
2994 getRenderEngine().setSaturationMatrix(mat4());
2995 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002996 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07002997
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002998 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002999 break;
3000 }
3001 default:
3002 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003003 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003004 } else {
3005 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003006 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003007 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003008 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003009
Peiyong Lin00f9c022018-05-09 15:35:33 -07003010 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003011 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003012 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07003013 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3014 getRenderEngine().setSaturationMatrix(mat4());
3015 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003016
Mathias Agopianf45c5102012-10-24 16:29:17 -07003017 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003018 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003019 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003020}
3021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003022void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3023 const Region& region) const {
3024 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003025 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003026 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003027}
3028
Dan Stoza7d89d062015-04-30 13:29:25 -07003029status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003030 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003031 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003032 const sp<Layer>& lbc,
3033 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003034{
Dan Stoza7d89d062015-04-30 13:29:25 -07003035 // add this layer to the current state list
3036 {
3037 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003038 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003039 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3040 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003041 return NO_MEMORY;
3042 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003043 if (parent == nullptr) {
3044 mCurrentState.layersSortedByZ.add(lbc);
3045 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003046 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003047 ALOGE("addClientLayer called with a removed parent");
3048 return NAME_NOT_FOUND;
3049 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003050 parent->addChild(lbc);
3051 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003052
Yiwei Zhang243b3782018-05-15 17:40:04 -07003053 if (gbc != nullptr) {
3054 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3055 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3056 mMaxGraphicBufferProducerListSize,
3057 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3058 mGraphicBufferProducerList.size(),
3059 mMaxGraphicBufferProducerListSize, mNumLayers);
3060 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003061 mLayersAdded = true;
3062 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003063 }
3064
Mathias Agopian96f08192010-06-02 23:28:45 -07003065 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003066 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003067
Dan Stoza7d89d062015-04-30 13:29:25 -07003068 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003069}
3070
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003071status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003072 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003073 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3074}
Robert Carr7f9b8992017-03-10 11:08:39 -08003075
chaviwca27f252018-02-06 16:46:39 -08003076status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3077 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003078 if (layer->isPendingRemoval()) {
3079 return NO_ERROR;
3080 }
3081
Robert Carr1f0a16a2016-10-24 16:27:39 -07003082 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003083 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003084 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003085 if (topLevelOnly) {
3086 return NO_ERROR;
3087 }
3088
Chia-I Wu98f1c102017-05-30 14:54:08 -07003089 sp<Layer> ancestor = p;
3090 while (ancestor->getParent() != nullptr) {
3091 ancestor = ancestor->getParent();
3092 }
3093 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3094 ALOGE("removeLayer called with a layer whose parent has been removed");
3095 return NAME_NOT_FOUND;
3096 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003097
3098 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003099 } else {
3100 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003101 }
3102
Robert Carr136e2f62017-02-08 17:54:29 -08003103 // As a matter of normal operation, the LayerCleaner will produce a second
3104 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3105 // so we will succeed in promoting it, but it's already been removed
3106 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3107 // otherwise something has gone wrong and we are leaking the layer.
3108 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003109 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3110 layer->getName().string(),
3111 (p != nullptr) ? p->getName().string() : "no-parent");
3112 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003113 } else if (index < 0) {
3114 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003115 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003116
Chia-I Wuc6657022017-08-15 11:18:17 -07003117 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003118 mLayersPendingRemoval.add(layer);
3119 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003120 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003121 setTransactionFlags(eTransactionNeeded);
3122 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003123}
3124
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003125uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003126 return android_atomic_release_load(&mTransactionFlags);
3127}
3128
Mathias Agopian3f844832013-08-07 21:24:32 -07003129uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003130 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3131}
3132
Mathias Agopian3f844832013-08-07 21:24:32 -07003133uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003134 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3135}
3136
3137uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3138 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003140 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003141 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003142 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143 }
3144 return old;
3145}
3146
chaviwca27f252018-02-06 16:46:39 -08003147bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3148 for (const ComposerState& state : states) {
3149 // Here we need to check that the interface we're given is indeed
3150 // one of our own. A malicious client could give us a nullptr
3151 // IInterface, or one of its own or even one of our own but a
3152 // different type. All these situations would cause us to crash.
3153 if (state.client == nullptr) {
3154 return true;
3155 }
3156
3157 sp<IBinder> binder = IInterface::asBinder(state.client);
3158 if (binder == nullptr) {
3159 return true;
3160 }
3161
3162 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3163 return true;
3164 }
3165 }
3166 return false;
3167}
3168
Mathias Agopian8b33f032012-07-24 20:43:54 -07003169void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003170 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003171 const Vector<DisplayState>& displays,
3172 uint32_t flags)
3173{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003174 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003175 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003176 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003177
chaviwca27f252018-02-06 16:46:39 -08003178 if (containsAnyInvalidClientState(states)) {
3179 return;
3180 }
3181
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003182 if (flags & eAnimation) {
3183 // For window updates that are part of an animation we must wait for
3184 // previous animation "frames" to be handled.
3185 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003186 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003187 if (CC_UNLIKELY(err != NO_ERROR)) {
3188 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003189 // caller after a few seconds.
3190 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3191 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003192 mAnimTransactionPending = false;
3193 break;
3194 }
3195 }
3196 }
3197
chaviwca27f252018-02-06 16:46:39 -08003198 for (const DisplayState& display : displays) {
3199 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003200 }
3201
chaviwca27f252018-02-06 16:46:39 -08003202 for (const ComposerState& state : states) {
3203 transactionFlags |= setClientStateLocked(state);
3204 }
3205
3206 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3207 // as destroyed should only occur after setting all other states. This is to allow for a
3208 // child re-parent to happen before marking its original parent as destroyed (which would
3209 // then mark the child as destroyed).
3210 for (const ComposerState& state : states) {
3211 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003212 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003213
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003214 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3215 // anyway. This can be used as a flush mechanism for previous async transactions.
3216 // Empty animation transaction can be used to simulate back-pressure, so also force a
3217 // transaction for empty animation transactions.
3218 if (transactionFlags == 0 &&
3219 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003220 transactionFlags = eTransactionNeeded;
3221 }
3222
Mathias Agopian386aa982011-11-07 21:58:03 -08003223 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003224 if (mInterceptor->isEnabled()) {
3225 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003226 }
Irvel468051e2016-06-13 16:44:44 -07003227
Mathias Agopian386aa982011-11-07 21:58:03 -08003228 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003229 const auto start = (flags & eEarlyWakeup)
3230 ? VSyncModulator::TransactionStart::EARLY
3231 : VSyncModulator::TransactionStart::NORMAL;
3232 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003233
3234 // if this is a synchronous transaction, wait for it to take effect
3235 // before returning.
3236 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003237 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003238 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003239 if (flags & eAnimation) {
3240 mAnimTransactionPending = true;
3241 }
3242 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003243 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3244 if (CC_UNLIKELY(err != NO_ERROR)) {
3245 // just in case something goes wrong in SF, return to the
3246 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003247 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3248 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003249 break;
3250 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003251 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252 }
3253}
3254
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003255uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3256 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3257 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003258
Mathias Agopiane57f2922012-08-09 16:29:12 -07003259 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003260 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3261
3262 const uint32_t what = s.what;
3263 if (what & DisplayState::eSurfaceChanged) {
3264 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3265 state.surface = s.surface;
3266 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003267 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003268 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003269 if (what & DisplayState::eLayerStackChanged) {
3270 if (state.layerStack != s.layerStack) {
3271 state.layerStack = s.layerStack;
3272 flags |= eDisplayTransactionNeeded;
3273 }
3274 }
3275 if (what & DisplayState::eDisplayProjectionChanged) {
3276 if (state.orientation != s.orientation) {
3277 state.orientation = s.orientation;
3278 flags |= eDisplayTransactionNeeded;
3279 }
3280 if (state.frame != s.frame) {
3281 state.frame = s.frame;
3282 flags |= eDisplayTransactionNeeded;
3283 }
3284 if (state.viewport != s.viewport) {
3285 state.viewport = s.viewport;
3286 flags |= eDisplayTransactionNeeded;
3287 }
3288 }
3289 if (what & DisplayState::eDisplaySizeChanged) {
3290 if (state.width != s.width) {
3291 state.width = s.width;
3292 flags |= eDisplayTransactionNeeded;
3293 }
3294 if (state.height != s.height) {
3295 state.height = s.height;
3296 flags |= eDisplayTransactionNeeded;
3297 }
3298 }
3299
Mathias Agopiane57f2922012-08-09 16:29:12 -07003300 return flags;
3301}
3302
chaviwca27f252018-02-06 16:46:39 -08003303uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3304 const layer_state_t& s = composerState.state;
3305 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3306
Mathias Agopian13127d82013-03-05 17:47:11 -08003307 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003308 if (layer == nullptr) {
3309 return 0;
3310 }
3311
3312 if (layer->isPendingRemoval()) {
3313 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3314 return 0;
3315 }
3316
3317 uint32_t flags = 0;
3318
3319 const uint32_t what = s.what;
3320 bool geometryAppliesWithResize =
3321 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003322
3323 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3324 // pending state will also be deferred.
3325 if (what & layer_state_t::eDeferTransaction) {
3326 layer->pushPendingState();
3327 }
3328
chaviw8b3871a2017-11-01 17:41:01 -07003329 if (what & layer_state_t::ePositionChanged) {
3330 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3331 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003332 }
chaviw8b3871a2017-11-01 17:41:01 -07003333 }
3334 if (what & layer_state_t::eLayerChanged) {
3335 // NOTE: index needs to be calculated before we update the state
3336 const auto& p = layer->getParent();
3337 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003338 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003339 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003340 mCurrentState.layersSortedByZ.removeAt(idx);
3341 mCurrentState.layersSortedByZ.add(layer);
3342 // we need traversal (state changed)
3343 // AND transaction (list changed)
3344 flags |= eTransactionNeeded|eTraversalNeeded;
3345 }
chaviw8b3871a2017-11-01 17:41:01 -07003346 } else {
3347 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003348 flags |= eTransactionNeeded|eTraversalNeeded;
3349 }
3350 }
chaviw8b3871a2017-11-01 17:41:01 -07003351 }
3352 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003353 // NOTE: index needs to be calculated before we update the state
3354 const auto& p = layer->getParent();
3355 if (p == nullptr) {
3356 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3357 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3358 mCurrentState.layersSortedByZ.removeAt(idx);
3359 mCurrentState.layersSortedByZ.add(layer);
3360 // we need traversal (state changed)
3361 // AND transaction (list changed)
3362 flags |= eTransactionNeeded|eTraversalNeeded;
3363 }
3364 } else {
3365 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3366 flags |= eTransactionNeeded|eTraversalNeeded;
3367 }
chaviw8b3871a2017-11-01 17:41:01 -07003368 }
3369 }
3370 if (what & layer_state_t::eSizeChanged) {
3371 if (layer->setSize(s.w, s.h)) {
3372 flags |= eTraversalNeeded;
3373 }
3374 }
3375 if (what & layer_state_t::eAlphaChanged) {
3376 if (layer->setAlpha(s.alpha))
3377 flags |= eTraversalNeeded;
3378 }
3379 if (what & layer_state_t::eColorChanged) {
3380 if (layer->setColor(s.color))
3381 flags |= eTraversalNeeded;
3382 }
3383 if (what & layer_state_t::eMatrixChanged) {
3384 if (layer->setMatrix(s.matrix))
3385 flags |= eTraversalNeeded;
3386 }
3387 if (what & layer_state_t::eTransparentRegionChanged) {
3388 if (layer->setTransparentRegionHint(s.transparentRegion))
3389 flags |= eTraversalNeeded;
3390 }
3391 if (what & layer_state_t::eFlagsChanged) {
3392 if (layer->setFlags(s.flags, s.mask))
3393 flags |= eTraversalNeeded;
3394 }
3395 if (what & layer_state_t::eCropChanged) {
3396 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3397 flags |= eTraversalNeeded;
3398 }
3399 if (what & layer_state_t::eFinalCropChanged) {
3400 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3401 flags |= eTraversalNeeded;
3402 }
3403 if (what & layer_state_t::eLayerStackChanged) {
3404 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3405 // We only allow setting layer stacks for top level layers,
3406 // everything else inherits layer stack from its parent.
3407 if (layer->hasParent()) {
3408 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3409 layer->getName().string());
3410 } else if (idx < 0) {
3411 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3412 "that also does not appear in the top level layer list. Something"
3413 " has gone wrong.", layer->getName().string());
3414 } else if (layer->setLayerStack(s.layerStack)) {
3415 mCurrentState.layersSortedByZ.removeAt(idx);
3416 mCurrentState.layersSortedByZ.add(layer);
3417 // we need traversal (state changed)
3418 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003419 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003420 }
3421 }
3422 if (what & layer_state_t::eDeferTransaction) {
3423 if (s.barrierHandle != nullptr) {
3424 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3425 } else if (s.barrierGbp != nullptr) {
3426 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3427 if (authenticateSurfaceTextureLocked(gbp)) {
3428 const auto& otherLayer =
3429 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3430 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3431 } else {
3432 ALOGE("Attempt to defer transaction to to an"
3433 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003434 }
3435 }
chaviw8b3871a2017-11-01 17:41:01 -07003436 // We don't trigger a traversal here because if no other state is
3437 // changed, we don't want this to cause any more work
3438 }
3439 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003440 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003441 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003442 if (!hadParent) {
3443 mCurrentState.layersSortedByZ.remove(layer);
3444 }
chaviw8b3871a2017-11-01 17:41:01 -07003445 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003446 }
chaviw8b3871a2017-11-01 17:41:01 -07003447 }
3448 if (what & layer_state_t::eReparentChildren) {
3449 if (layer->reparentChildren(s.reparentHandle)) {
3450 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003451 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003452 }
chaviw8b3871a2017-11-01 17:41:01 -07003453 if (what & layer_state_t::eDetachChildren) {
3454 layer->detachChildren();
3455 }
3456 if (what & layer_state_t::eOverrideScalingModeChanged) {
3457 layer->setOverrideScalingMode(s.overrideScalingMode);
3458 // We don't trigger a traversal here because if no other state is
3459 // changed, we don't want this to cause any more work
3460 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003461 return flags;
3462}
3463
chaviwca27f252018-02-06 16:46:39 -08003464void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3465 const layer_state_t& state = composerState.state;
3466 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3467
3468 sp<Layer> layer(client->getLayerUser(state.surface));
3469 if (layer == nullptr) {
3470 return;
3471 }
3472
3473 if (layer->isPendingRemoval()) {
3474 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3475 return;
3476 }
3477
3478 if (state.what & layer_state_t::eDestroySurface) {
3479 removeLayerLocked(mStateLock, layer);
3480 }
3481}
3482
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003483status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003484 const String8& name,
3485 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003486 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003487 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003488 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003489{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003490 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003491 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003492 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003493 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003494 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003495
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003496 status_t result = NO_ERROR;
3497
3498 sp<Layer> layer;
3499
Cody Northropbc755282017-03-31 12:00:08 -06003500 String8 uniqueName = getUniqueLayerName(name);
3501
Mathias Agopian3165cc22012-08-08 19:42:09 -07003502 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3503 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003504 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003505 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003506 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003507
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003508 break;
chaviw13fdc492017-06-27 12:40:18 -07003509 case ISurfaceComposerClient::eFXSurfaceColor:
3510 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003511 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003512 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003513 break;
3514 default:
3515 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003516 break;
3517 }
3518
Dan Stoza7d89d062015-04-30 13:29:25 -07003519 if (result != NO_ERROR) {
3520 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003522
Chia-I Wuab0c3192017-08-01 11:29:00 -07003523 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3524 // TODO b/64227542
3525 if (windowType == 441731) {
3526 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3527 layer->setPrimaryDisplayOnly();
3528 }
3529
Albert Chaulk479c60c2017-01-27 14:21:34 -05003530 layer->setInfo(windowType, ownerUid);
3531
Robert Carr1f0a16a2016-10-24 16:27:39 -07003532 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003533 if (result != NO_ERROR) {
3534 return result;
3535 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003536 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003537
3538 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003539 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003540}
3541
Cody Northropbc755282017-03-31 12:00:08 -06003542String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3543{
3544 bool matchFound = true;
3545 uint32_t dupeCounter = 0;
3546
3547 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3548 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3549
Dan Stoza436ccf32018-06-21 12:10:12 -07003550 // Grab the state lock since we're accessing mCurrentState
3551 Mutex::Autolock lock(mStateLock);
3552
Cody Northropbc755282017-03-31 12:00:08 -06003553 // Loop over layers until we're sure there is no matching name
3554 while (matchFound) {
3555 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003556 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003557 if (layer->getName() == uniqueName) {
3558 matchFound = true;
3559 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3560 }
3561 });
3562 }
3563
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003564 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3565 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003566
3567 return uniqueName;
3568}
3569
David Sodman0c69cad2017-08-21 12:12:51 -07003570status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003571 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3572 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003573{
3574 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003575 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576 case PIXEL_FORMAT_TRANSPARENT:
3577 case PIXEL_FORMAT_TRANSLUCENT:
3578 format = PIXEL_FORMAT_RGBA_8888;
3579 break;
3580 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003581 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003582 break;
3583 }
3584
David Sodman0c69cad2017-08-21 12:12:51 -07003585 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3586 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003587 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003588 *handle = layer->getHandle();
3589 *gbp = layer->getProducer();
3590 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003591 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003592
David Sodman0c69cad2017-08-21 12:12:51 -07003593 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003594 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003595}
3596
chaviw13fdc492017-06-27 12:40:18 -07003597status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003598 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003599 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003600{
chaviw13fdc492017-06-27 12:40:18 -07003601 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003602 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003603 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003604}
3605
Mathias Agopianac9fa422013-02-11 16:40:36 -08003606status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003607{
Robert Carr9524cb32017-02-13 11:32:32 -08003608 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003609 status_t err = NO_ERROR;
3610 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003611 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003612 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003613 err = removeLayer(l);
3614 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3615 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003616 }
3617 return err;
3618}
3619
Mathias Agopian13127d82013-03-05 17:47:11 -08003620status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003621{
Mathias Agopian67106042013-03-14 19:18:13 -07003622 // called by ~LayerCleaner() when all references to the IBinder (handle)
3623 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003624 sp<Layer> l = layer.promote();
3625 if (l == nullptr) {
3626 // The layer has already been removed, carry on
3627 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003628 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003629 // If we have a parent, then we can continue to live as long as it does.
3630 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003631}
3632
Mathias Agopianb60314a2012-04-10 22:09:54 -07003633// ---------------------------------------------------------------------------
3634
Andy McFadden13a082e2012-08-24 10:16:42 -07003635void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003636 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3637 if (!displayToken) return;
3638
Jesse Hall01e29052013-02-19 16:13:35 -08003639 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003640 Vector<ComposerState> state;
3641 Vector<DisplayState> displays;
3642 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003643 d.what = DisplayState::eDisplayProjectionChanged |
3644 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003645 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003646 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003647 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003648 d.frame.makeInvalid();
3649 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003650 d.width = 0;
3651 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003652 displays.add(d);
3653 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003654
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003655 const auto display = getDisplayDevice(displayToken);
3656 if (!display) return;
3657
3658 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3659
3660 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003661 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003662 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003663
Brian Andersond0010582017-03-07 13:20:31 -08003664 // Use phase of 0 since phase is not known.
3665 // Use latency of 0, which will snap to the ideal latency.
3666 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003667}
3668
3669void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003670 // Async since we may be called from the main thread.
3671 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003672}
3673
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003674void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3675 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003676 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003677 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003678
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003679 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003680 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003681 return;
3682 }
3683
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003684 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003685 ALOGW("Trying to set power mode for virtual display");
3686 return;
3687 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003688
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003689 display->setPowerMode(mode);
3690
Lloyd Pique4dccc412018-01-22 17:21:36 -08003691 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003692 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003693 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003694 if (idx < 0) {
3695 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3696 return;
3697 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003698 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003699 }
3700
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003701 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003702 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003703 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003704 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003705 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003706 // FIXME: eventthread only knows about the main display right now
3707 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003708 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003709 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003710
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003711 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003712 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003713 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003714
3715 struct sched_param param = {0};
3716 param.sched_priority = 1;
3717 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3718 ALOGW("Couldn't set SCHED_FIFO on display on");
3719 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003720 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003721 // Turn off the display
3722 struct sched_param param = {0};
3723 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3724 ALOGW("Couldn't set SCHED_OTHER on display off");
3725 }
3726
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003727 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003728 disableHardwareVsync(true); // also cancels any in-progress resync
3729
Mathias Agopiancde87a32012-09-13 14:09:01 -07003730 // FIXME: eventthread only knows about the main display right now
3731 mEventThread->onScreenReleased();
3732 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003733
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003734 getHwComposer().setPowerMode(type, mode);
3735 mVisibleRegionsDirty = true;
3736 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003737 } else if (mode == HWC_POWER_MODE_DOZE ||
3738 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003739 // Update display while dozing
3740 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003741 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003742 // FIXME: eventthread only knows about the main display right now
3743 mEventThread->onScreenAcquired();
3744 resyncToHardwareVsync(true);
3745 }
3746 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3747 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003748 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003749 disableHardwareVsync(true); // also cancels any in-progress resync
3750 // FIXME: eventthread only knows about the main display right now
3751 mEventThread->onScreenReleased();
3752 }
3753 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003754 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003755 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003756 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003757 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003758
3759 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003760}
3761
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003762void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003763 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003764 const auto display = getDisplayDevice(displayToken);
3765 if (!display) {
3766 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3767 displayToken.get());
3768 } else if (display->isVirtual()) {
3769 ALOGW("Attempt to set power mode %d for virtual display", mode);
3770 } else {
3771 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003772 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003773 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003774}
3775
3776// ---------------------------------------------------------------------------
3777
Lloyd Pique755e3192018-01-31 16:46:15 -08003778status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3779 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003780 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003781
Mathias Agopianbd115332013-04-18 16:41:04 -07003782 IPCThreadState* ipc = IPCThreadState::self();
3783 const int pid = ipc->getCallingPid();
3784 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003785
Mathias Agopianbd115332013-04-18 16:41:04 -07003786 if ((uid != AID_SHELL) &&
3787 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003788 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003789 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003790 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003791 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003792 // (this would indicate SF is stuck, but we want to be able to
3793 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003794 status_t err = mStateLock.timedLock(s2ns(1));
3795 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003796 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003797 result.appendFormat(
3798 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3799 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003800 }
3801
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003802 bool dumpAll = true;
3803 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003804 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003805
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003806 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003807 if ((index < numArgs) &&
3808 (args[index] == String16("--list"))) {
3809 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003810 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003811 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003812 }
3813
3814 if ((index < numArgs) &&
3815 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003816 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003817 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003818 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003819 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003820
3821 if ((index < numArgs) &&
3822 (args[index] == String16("--latency-clear"))) {
3823 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003824 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003825 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003826 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003827
3828 if ((index < numArgs) &&
3829 (args[index] == String16("--dispsync"))) {
3830 index++;
3831 mPrimaryDispSync.dump(result);
3832 dumpAll = false;
3833 }
Dan Stozab90cf072015-03-05 11:05:59 -08003834
3835 if ((index < numArgs) &&
3836 (args[index] == String16("--static-screen"))) {
3837 index++;
3838 dumpStaticScreenStats(result);
3839 dumpAll = false;
3840 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003841
3842 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003843 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003844 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003845 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003846 dumpAll = false;
3847 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003848
3849 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3850 index++;
3851 dumpWideColorInfo(result);
3852 dumpAll = false;
3853 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003854
3855 if ((index < numArgs) &&
3856 (args[index] == String16("--enable-layer-stats"))) {
3857 index++;
3858 mLayerStats.enable();
3859 dumpAll = false;
3860 }
3861
3862 if ((index < numArgs) &&
3863 (args[index] == String16("--disable-layer-stats"))) {
3864 index++;
3865 mLayerStats.disable();
3866 dumpAll = false;
3867 }
3868
3869 if ((index < numArgs) &&
3870 (args[index] == String16("--clear-layer-stats"))) {
3871 index++;
3872 mLayerStats.clear();
3873 dumpAll = false;
3874 }
3875
3876 if ((index < numArgs) &&
3877 (args[index] == String16("--dump-layer-stats"))) {
3878 index++;
3879 mLayerStats.dump(result);
3880 dumpAll = false;
3881 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003882
3883 if ((index < numArgs) &&
3884 (args[index] == String16("--display-identification"))) {
3885 index++;
3886 dumpDisplayIdentificationData(result);
3887 dumpAll = false;
3888 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003889
3890 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3891 index++;
3892 mTimeStats.parseArgs(asProto, args, index, result);
3893 dumpAll = false;
3894 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003895 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003896
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003897 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003898 if (asProto) {
3899 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3900 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3901 } else {
3902 dumpAllLocked(args, index, result);
3903 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003904 }
3905
Mathias Agopian9795c422009-08-26 16:36:26 -07003906 if (locked) {
3907 mStateLock.unlock();
3908 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003909 }
3910 write(fd, result.string(), result.size());
3911 return NO_ERROR;
3912}
3913
Dan Stozac7014012014-02-14 15:03:43 -08003914void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3915 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003916{
Robert Carr2047fae2016-11-28 14:09:09 -08003917 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003918 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003919 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003920}
3921
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003922void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003923 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003924{
3925 String8 name;
3926 if (index < args.size()) {
3927 name = String8(args[index]);
3928 index++;
3929 }
3930
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003931 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3932 getHwComposer().isConnected(displayId)) {
3933 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3934 const nsecs_t period = activeConfig->getVsyncPeriod();
3935 result.appendFormat("%" PRId64 "\n", period);
3936 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003937
3938 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003939 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003940 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003941 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003942 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003943 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003944 }
Robert Carr2047fae2016-11-28 14:09:09 -08003945 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003946 }
3947}
3948
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003949void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003950 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003951{
3952 String8 name;
3953 if (index < args.size()) {
3954 name = String8(args[index]);
3955 index++;
3956 }
3957
Robert Carr2047fae2016-11-28 14:09:09 -08003958 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003959 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003960 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003961 }
Robert Carr2047fae2016-11-28 14:09:09 -08003962 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003963
Svetoslavd85084b2014-03-20 10:28:31 -07003964 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003965}
3966
Jamie Gennis6547ff42013-07-16 20:12:42 -07003967// This should only be called from the main thread. Otherwise it would need
3968// the lock and should use mCurrentState rather than mDrawingState.
3969void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003970 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003971 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003972 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003973
3974 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3975}
3976
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003977void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003978{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003979 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003980
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003981 if (isLayerTripleBufferingDisabled())
3982 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003983
3984 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003985 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003986 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003987 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003988 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3989 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003990 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003991}
3992
Dan Stozab90cf072015-03-05 11:05:59 -08003993void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3994{
3995 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003996 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3997 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003998 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003999 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004000 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4001 b + 1, bucketTimeSec, percent);
4002 }
David Sodman4a36e932017-11-07 14:29:47 -08004003 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004004 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004005 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004006 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004007 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004008}
4009
Dan Stozae77c7662016-05-13 11:37:28 -07004010void SurfaceFlinger::recordBufferingStats(const char* layerName,
4011 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004012 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4013 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004014 for (const auto& segment : history) {
4015 if (!segment.usedThirdBuffer) {
4016 stats.twoBufferTime += segment.totalTime;
4017 }
4018 if (segment.occupancyAverage < 1.0f) {
4019 stats.doubleBufferedTime += segment.totalTime;
4020 } else if (segment.occupancyAverage < 2.0f) {
4021 stats.tripleBufferedTime += segment.totalTime;
4022 }
4023 ++stats.numSegments;
4024 stats.totalTime += segment.totalTime;
4025 }
4026}
4027
Brian Andersond6927fb2016-07-23 23:37:30 -07004028void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4029 result.appendFormat("Layer frame timestamps:\n");
4030
4031 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4032 const size_t count = currentLayers.size();
4033 for (size_t i=0 ; i<count ; i++) {
4034 currentLayers[i]->dumpFrameEvents(result);
4035 }
4036}
4037
Dan Stozae77c7662016-05-13 11:37:28 -07004038void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4039 result.append("Buffering stats:\n");
4040 result.append(" [Layer name] <Active time> <Two buffer> "
4041 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004042 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004043 typedef std::tuple<std::string, float, float, float> BufferTuple;
4044 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004045 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004046 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004047 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004048 if (stats.numSegments == 0) {
4049 continue;
4050 }
4051 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4052 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4053 stats.totalTime;
4054 float doubleBufferRatio = static_cast<float>(
4055 stats.doubleBufferedTime) / stats.totalTime;
4056 float tripleBufferRatio = static_cast<float>(
4057 stats.tripleBufferedTime) / stats.totalTime;
4058 sorted.insert({activeTime, {name, twoBufferRatio,
4059 doubleBufferRatio, tripleBufferRatio}});
4060 }
4061 for (const auto& sortedPair : sorted) {
4062 float activeTime = sortedPair.first;
4063 const BufferTuple& values = sortedPair.second;
4064 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4065 std::get<0>(values).c_str(), activeTime,
4066 std::get<1>(values), std::get<2>(values),
4067 std::get<3>(values));
4068 }
4069 result.append("\n");
4070}
4071
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004072void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004073 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004074 const int32_t displayId = display->getId();
4075 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4076 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004077 continue;
4078 }
4079
Dominik Laskowski7e045462018-05-30 13:02:02 -07004080 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004081 uint8_t port;
4082 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004083 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004084 result.append("no identification data\n");
4085 continue;
4086 }
4087
4088 if (!isEdid(data)) {
4089 result.append("unknown identification data: ");
4090 for (uint8_t byte : data) {
4091 result.appendFormat("%x ", byte);
4092 }
4093 result.append("\n");
4094 continue;
4095 }
4096
4097 const auto edid = parseEdid(data);
4098 if (!edid) {
4099 result.append("invalid EDID: ");
4100 for (uint8_t byte : data) {
4101 result.appendFormat("%x ", byte);
4102 }
4103 result.append("\n");
4104 continue;
4105 }
4106
4107 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4108 result.append(edid->displayName.data(), edid->displayName.length());
4109 result.append("\"\n");
4110 }
4111 result.append("\n");
4112}
4113
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004114void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4115 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004116 result.appendFormat("DisplayColorSetting: %s\n",
4117 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004118
4119 // TODO: print out if wide-color mode is active or not
4120
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004121 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004122 const int32_t displayId = display->getId();
4123 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004124 continue;
4125 }
4126
Dominik Laskowski7e045462018-05-30 13:02:02 -07004127 result.appendFormat("Display %d color modes:\n", displayId);
4128 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004129 for (auto&& mode : modes) {
4130 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4131 }
4132
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004133 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004134 result.appendFormat(" Current color mode: %s (%d)\n",
4135 decodeColorMode(currentMode).c_str(), currentMode);
4136 }
4137 result.append("\n");
4138}
4139
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004140LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004141 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004142 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4143 const State& state = useDrawing ? mDrawingState : mCurrentState;
4144 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004145 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004146 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004147 });
4148
4149 return layersProto;
4150}
4151
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004152LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004153 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004154
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004155 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004156 resolution->set_w(display.getWidth());
4157 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004158
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004159 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4160 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4161 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004162
Dominik Laskowski7e045462018-05-30 13:02:02 -07004163 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004164 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004165 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004166 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004167 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004168 }
4169 });
4170
4171 return layersProto;
4172}
4173
Mathias Agopian74d211a2013-04-22 16:55:35 +02004174void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4175 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004176{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004177 bool colorize = false;
4178 if (index < args.size()
4179 && (args[index] == String16("--color"))) {
4180 colorize = true;
4181 index++;
4182 }
4183
4184 Colorizer colorizer(colorize);
4185
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004186 // figure out if we're stuck somewhere
4187 const nsecs_t now = systemTime();
4188 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4189 const nsecs_t inTransaction(mDebugInTransaction);
4190 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4191 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4192
4193 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004194 * Dump library configuration.
4195 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004196
4197 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004198 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004199 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004200 appendSfConfigString(result);
4201 appendUiConfigString(result);
4202 appendGuiConfigString(result);
4203 result.append("\n");
4204
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004205 result.append("\nDisplay identification data:\n");
4206 dumpDisplayIdentificationData(result);
4207
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004208 result.append("\nWide-Color information:\n");
4209 dumpWideColorInfo(result);
4210
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004211 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004212 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004213 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004214 result.append(SyncFeatures::getInstance().toString());
4215 result.append("\n");
4216
Andy McFadden41d67d72014-04-25 16:58:34 -07004217 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004218 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004219 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004220
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004221 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4222 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004223 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4224 getHwComposer().isConnected(displayId)) {
4225 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004226 result.appendFormat("Display %d: "
4227 "app phase %" PRId64 " ns, "
4228 "sf phase %" PRId64 " ns, "
4229 "early app phase %" PRId64 " ns, "
4230 "early sf phase %" PRId64 " ns, "
4231 "early app gl phase %" PRId64 " ns, "
4232 "early sf gl phase %" PRId64 " ns, "
4233 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4234 displayId,
4235 vsyncPhaseOffsetNs,
4236 sfVsyncPhaseOffsetNs,
4237 appEarlyOffset,
4238 sfEarlyOffset,
4239 appEarlyGlOffset,
4240 sfEarlyOffset,
4241 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004242 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004243 result.append("\n");
4244
Dan Stozab90cf072015-03-05 11:05:59 -08004245 // Dump static screen stats
4246 result.append("\n");
4247 dumpStaticScreenStats(result);
4248 result.append("\n");
4249
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004250 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4251
Dan Stozae77c7662016-05-13 11:37:28 -07004252 dumpBufferingStats(result);
4253
Andy McFadden4803b742012-09-24 19:07:20 -07004254 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004255 * Dump the visible layer list
4256 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004257 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004258 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004259 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4260 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004261 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004262
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004263 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004264 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004265 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004266 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004267
4268 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004269 * Dump Display state
4270 */
4271
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004272 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004273 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004274 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004275 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004276 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004277 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004278 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004279
4280 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004281 * Dump SurfaceFlinger global state
4282 */
4283
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004284 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004285 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004286 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004287
Mathias Agopian888c8222012-08-04 21:10:38 -07004288 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004289 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004290
David Sodmanbc815282017-11-05 18:57:52 -08004291 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004292
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004293 if (display) {
4294 display->undefinedRegion.dump(result, "undefinedRegion");
4295 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4296 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004297 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004298 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4299 " last transaction time : %f us\n"
4300 " transaction-flags : %08x\n"
4301 " gpu_to_cpu_unsupported : %d\n",
4302 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4303 mTransactionFlags, !mGpuToCpuSupported);
4304
4305 if (display) {
4306 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4307 result.appendFormat(" refresh-rate : %f fps\n"
4308 " x-dpi : %f\n"
4309 " y-dpi : %f\n",
4310 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4311 activeConfig->getDpiY());
4312 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004313
Mathias Agopian74d211a2013-04-22 16:55:35 +02004314 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004315 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004316
Mathias Agopian74d211a2013-04-22 16:55:35 +02004317 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004318 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004319
4320 /*
4321 * VSYNC state
4322 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004323 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004324 result.append("\n");
4325
4326 /*
4327 * HWC layer minidump
4328 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004329 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004330 const int32_t displayId = display->getId();
4331 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004332 continue;
4333 }
4334
Dominik Laskowski7e045462018-05-30 13:02:02 -07004335 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004336 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004337 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004338 result.append("\n");
4339 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004340
4341 /*
4342 * Dump HWComposer state
4343 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004344 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004345 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004346 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004347 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004348 result.appendFormat(" h/w composer %s\n",
4349 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004350 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004351
4352 /*
4353 * Dump gralloc state
4354 */
4355 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4356 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004357
4358 /*
4359 * Dump VrFlinger state if in use.
4360 */
4361 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4362 result.append("VrFlinger state:\n");
4363 result.append(mVrFlinger->Dump().c_str());
4364 result.append("\n");
4365 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004366}
4367
Dominik Laskowski7e045462018-05-30 13:02:02 -07004368const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004369 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004370 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004371 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004372 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004373 }
4374 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004375
4376 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4377 static const Vector<sp<Layer>> empty;
4378 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004379}
4380
Keun young Park63f165f2012-08-31 10:53:36 -07004381bool SurfaceFlinger::startDdmConnection()
4382{
4383 void* libddmconnection_dso =
4384 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4385 if (!libddmconnection_dso) {
4386 return false;
4387 }
4388 void (*DdmConnection_start)(const char* name);
4389 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004390 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004391 if (!DdmConnection_start) {
4392 dlclose(libddmconnection_dso);
4393 return false;
4394 }
4395 (*DdmConnection_start)(getServiceName());
4396 return true;
4397}
4398
Chia-I Wu28f320b2018-05-03 11:02:56 -07004399void SurfaceFlinger::updateColorMatrixLocked() {
4400 mat4 colorMatrix;
4401 if (mGlobalSaturationFactor != 1.0f) {
4402 // Rec.709 luma coefficients
4403 float3 luminance{0.213f, 0.715f, 0.072f};
4404 luminance *= 1.0f - mGlobalSaturationFactor;
4405 mat4 saturationMatrix = mat4(
4406 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4407 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4408 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4409 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4410 );
4411 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4412 } else {
4413 colorMatrix = mClientColorMatrix * mDaltonizer();
4414 }
4415
4416 if (mCurrentState.colorMatrix != colorMatrix) {
4417 mCurrentState.colorMatrix = colorMatrix;
4418 mCurrentState.colorMatrixChanged = true;
4419 setTransactionFlags(eTransactionNeeded);
4420 }
4421}
4422
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004423status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004424 switch (code) {
4425 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004426 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004427 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004428 case CLEAR_ANIMATION_FRAME_STATS:
4429 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004430 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004431 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004432 case ENABLE_VSYNC_INJECTIONS:
4433 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004434 {
4435 // codes that require permission check
4436 IPCThreadState* ipc = IPCThreadState::self();
4437 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004438 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004439 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004440 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004441 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004442 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004443 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004444 break;
4445 }
Robert Carr1db73f62016-12-21 12:58:51 -08004446 /*
4447 * Calling setTransactionState is safe, because you need to have been
4448 * granted a reference to Client* and Handle* to do anything with it.
4449 *
4450 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4451 */
4452 case SET_TRANSACTION_STATE:
4453 case CREATE_SCOPED_CONNECTION:
4454 {
4455 return OK;
4456 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004457 case CAPTURE_SCREEN:
4458 {
4459 // codes that require permission check
4460 IPCThreadState* ipc = IPCThreadState::self();
4461 const int pid = ipc->getCallingPid();
4462 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004463 if ((uid != AID_GRAPHICS) &&
4464 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004465 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004466 return PERMISSION_DENIED;
4467 }
4468 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004469 }
chaviwa76b2712017-09-20 12:02:26 -07004470 case CAPTURE_LAYERS: {
4471 IPCThreadState* ipc = IPCThreadState::self();
4472 const int pid = ipc->getCallingPid();
4473 const int uid = ipc->getCallingUid();
4474 if ((uid != AID_GRAPHICS) &&
4475 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4476 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4477 return PERMISSION_DENIED;
4478 }
4479 break;
4480 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004481 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004482 return OK;
4483}
4484
4485status_t SurfaceFlinger::onTransact(
4486 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4487{
4488 status_t credentialCheck = CheckTransactCodeCredentials(code);
4489 if (credentialCheck != OK) {
4490 return credentialCheck;
4491 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004492
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004493 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4494 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004495 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004496 IPCThreadState* ipc = IPCThreadState::self();
4497 const int uid = ipc->getCallingUid();
4498 if (CC_UNLIKELY(uid != AID_SYSTEM
4499 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004500 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004501 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004502 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004503 return PERMISSION_DENIED;
4504 }
4505 int n;
4506 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004507 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004508 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004509 return NO_ERROR;
4510 case 1002: // SHOW_UPDATES
4511 n = data.readInt32();
4512 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004513 invalidateHwcGeometry();
4514 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004515 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004516 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004517 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004518 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004519 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004520 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004521 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004522 setTransactionFlags(
4523 eTransactionNeeded|
4524 eDisplayTransactionNeeded|
4525 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004526 return NO_ERROR;
4527 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004528 case 1006:{ // send empty update
4529 signalRefresh();
4530 return NO_ERROR;
4531 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004532 case 1008: // toggle use of hw composer
4533 n = data.readInt32();
4534 mDebugDisableHWC = n ? 1 : 0;
4535 invalidateHwcGeometry();
4536 repaintEverything();
4537 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004538 case 1009: // toggle use of transform hint
4539 n = data.readInt32();
4540 mDebugDisableTransformHint = n ? 1 : 0;
4541 invalidateHwcGeometry();
4542 repaintEverything();
4543 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004544 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004545 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004546 reply->writeInt32(0);
4547 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004548 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004549 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004550 return NO_ERROR;
4551 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004552 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004553 if (!display) {
4554 return NAME_NOT_FOUND;
4555 }
4556
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004557 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004558 return NO_ERROR;
4559 }
4560 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004561 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004562 // daltonize
4563 n = data.readInt32();
4564 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004565 case 1:
4566 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4567 break;
4568 case 2:
4569 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4570 break;
4571 case 3:
4572 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4573 break;
4574 default:
4575 mDaltonizer.setType(ColorBlindnessType::None);
4576 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004577 }
4578 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004579 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004580 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004581 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004582 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004583
4584 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004585 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004586 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004587 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004588 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004589 // apply a color matrix
4590 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004591 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004592 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004593 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004594 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004595 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004596 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004597 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004598 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004599 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004600 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004601
4602 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4603 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004604 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004605 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4606 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4607 }
4608
Chia-I Wu28f320b2018-05-03 11:02:56 -07004609 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004610 return NO_ERROR;
4611 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004612 // This is an experimental interface
4613 // Needs to be shifted to proper binder interface when we productize
4614 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004615 n = data.readInt32();
4616 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004617 return NO_ERROR;
4618 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004619 case 1017: {
4620 n = data.readInt32();
4621 mForceFullDamage = static_cast<bool>(n);
4622 return NO_ERROR;
4623 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004624 case 1018: { // Modify Choreographer's phase offset
4625 n = data.readInt32();
4626 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4627 return NO_ERROR;
4628 }
4629 case 1019: { // Modify SurfaceFlinger's phase offset
4630 n = data.readInt32();
4631 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4632 return NO_ERROR;
4633 }
Irvel468051e2016-06-13 16:44:44 -07004634 case 1020: { // Layer updates interceptor
4635 n = data.readInt32();
4636 if (n) {
4637 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004638 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004639 }
4640 else{
4641 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004642 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004643 }
4644 return NO_ERROR;
4645 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004646 case 1021: { // Disable HWC virtual displays
4647 n = data.readInt32();
4648 mUseHwcVirtualDisplays = !n;
4649 return NO_ERROR;
4650 }
Romain Guy0147a172017-06-01 13:53:56 -07004651 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004652 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004653 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004654
Chia-I Wu28f320b2018-05-03 11:02:56 -07004655 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004656 return NO_ERROR;
4657 }
Romain Guy54f154a2017-10-24 21:40:32 +01004658 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004659 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004660 invalidateHwcGeometry();
4661 repaintEverything();
4662 return NO_ERROR;
4663 }
4664 case 1024: { // Is wide color gamut rendering/color management supported?
4665 reply->writeBool(hasWideColorDisplay);
4666 return NO_ERROR;
4667 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004668 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004669 n = data.readInt32();
4670 if (n) {
4671 ALOGV("LayerTracing enabled");
4672 mTracing.enable();
4673 doTracing("tracing.enable");
4674 reply->writeInt32(NO_ERROR);
4675 } else {
4676 ALOGV("LayerTracing disabled");
4677 status_t err = mTracing.disable();
4678 reply->writeInt32(err);
4679 }
4680 return NO_ERROR;
4681 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004682 case 1026: { // Get layer tracing status
4683 reply->writeBool(mTracing.isEnabled());
4684 return NO_ERROR;
4685 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004686 // Is a DisplayColorSetting supported?
4687 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004688 const auto display = getDefaultDisplayDevice();
4689 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004690 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004691 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004692
4693 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4694 switch (setting) {
4695 case DisplayColorSetting::MANAGED:
4696 reply->writeBool(hasWideColorDisplay);
4697 break;
4698 case DisplayColorSetting::UNMANAGED:
4699 reply->writeBool(true);
4700 break;
4701 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004702 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004703 break;
4704 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004705 reply->writeBool(
4706 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004707 break;
4708 }
4709 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004710 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004711 // Is VrFlinger active?
4712 case 1028: {
4713 Mutex::Autolock _l(mStateLock);
4714 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4715 return NO_ERROR;
4716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004717 }
4718 }
4719 return err;
4720}
4721
Steven Thomas6d8110b2017-08-31 18:24:21 -07004722void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004723 android_atomic_or(1, &mRepaintEverything);
4724 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004725}
4726
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004727// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4728class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004729public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004730 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4731 ~WindowDisconnector() {
4732 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004733 }
4734
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004735private:
4736 ANativeWindow* mWindow;
4737 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004738};
4739
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004740status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4741 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4742 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4743 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004744 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004745 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004746
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004747 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004748
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004749 const auto display = getDisplayDeviceLocked(displayToken);
4750 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004751
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004752 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004753
4754 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004755 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004756 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004757}
4758
4759status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004760 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004761 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004762 ATRACE_CALL();
4763
4764 class LayerRenderArea : public RenderArea {
4765 public:
Robert Carr578038f2018-03-09 12:25:24 -08004766 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4767 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004768 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004769 mLayer(layer),
4770 mCrop(crop),
4771 mFlinger(flinger),
4772 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004773 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004774 Rect getBounds() const override {
4775 const Layer::State& layerState(mLayer->getDrawingState());
4776 return Rect(layerState.active.w, layerState.active.h);
4777 }
4778 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4779 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4780 bool isSecure() const override { return false; }
4781 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004782 Rect getSourceCrop() const override {
4783 if (mCrop.isEmpty()) {
4784 return getBounds();
4785 } else {
4786 return mCrop;
4787 }
4788 }
Robert Carr578038f2018-03-09 12:25:24 -08004789 class ReparentForDrawing {
4790 public:
4791 const sp<Layer>& oldParent;
4792 const sp<Layer>& newParent;
4793
4794 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4795 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004796 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004797 }
Robert Carr15eae092018-03-23 13:43:53 -07004798 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004799 };
4800
4801 void render(std::function<void()> drawLayers) override {
4802 if (!mChildrenOnly) {
4803 mTransform = mLayer->getTransform().inverse();
4804 drawLayers();
4805 } else {
4806 Rect bounds = getBounds();
4807 screenshotParentLayer =
4808 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4809 bounds.getWidth(), bounds.getHeight(), 0);
4810
4811 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4812 drawLayers();
4813 }
4814 }
chaviwa76b2712017-09-20 12:02:26 -07004815
chaviwa76b2712017-09-20 12:02:26 -07004816 private:
chaviw7206d492017-11-10 16:16:12 -08004817 const sp<Layer> mLayer;
4818 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004819
4820 // In the "childrenOnly" case we reparent the children to a screenshot
4821 // layer which has no properties set and which does not draw.
4822 sp<ContainerLayer> screenshotParentLayer;
4823 Transform mTransform;
4824
4825 SurfaceFlinger* mFlinger;
4826 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004827 };
4828
4829 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4830 auto parent = layerHandle->owner.promote();
4831
chaviw7206d492017-11-10 16:16:12 -08004832 if (parent == nullptr || parent->isPendingRemoval()) {
4833 ALOGE("captureLayers called with a removed parent");
4834 return NAME_NOT_FOUND;
4835 }
4836
Robert Carr578038f2018-03-09 12:25:24 -08004837 const int uid = IPCThreadState::self()->getCallingUid();
4838 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4839 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4840 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4841 return PERMISSION_DENIED;
4842 }
4843
chaviw7206d492017-11-10 16:16:12 -08004844 Rect crop(sourceCrop);
4845 if (sourceCrop.width() <= 0) {
4846 crop.left = 0;
4847 crop.right = parent->getCurrentState().active.w;
4848 }
4849
4850 if (sourceCrop.height() <= 0) {
4851 crop.top = 0;
4852 crop.bottom = parent->getCurrentState().active.h;
4853 }
4854
4855 int32_t reqWidth = crop.width() * frameScale;
4856 int32_t reqHeight = crop.height() * frameScale;
4857
Robert Carr578038f2018-03-09 12:25:24 -08004858 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004859
Robert Carr578038f2018-03-09 12:25:24 -08004860 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004861 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4862 if (!layer->isVisible()) {
4863 return;
Robert Carr578038f2018-03-09 12:25:24 -08004864 } else if (childrenOnly && layer == parent.get()) {
4865 return;
chaviwa76b2712017-09-20 12:02:26 -07004866 }
4867 visitor(layer);
4868 });
4869 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004870 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004871}
4872
4873status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4874 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004875 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004876 bool useIdentityTransform) {
4877 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004878
Iris Chang7501ed62018-04-30 14:45:42 +08004879 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004880
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004881 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4882 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4883 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4884 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004885
4886 // This mutex protects syncFd and captureResult for communication of the return values from the
4887 // main thread back to this Binder thread
4888 std::mutex captureMutex;
4889 std::condition_variable captureCondition;
4890 std::unique_lock<std::mutex> captureLock(captureMutex);
4891 int syncFd = -1;
4892 std::optional<status_t> captureResult;
4893
Robert Carr03480e22018-01-04 16:02:06 -08004894 const int uid = IPCThreadState::self()->getCallingUid();
4895 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4896
Dominik Laskowski8c001672018-05-30 16:52:06 -07004897 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004898 // If there is a refresh pending, bug out early and tell the binder thread to try again
4899 // after the refresh.
4900 if (mRefreshPending) {
4901 ATRACE_NAME("Skipping screenshot for now");
4902 std::unique_lock<std::mutex> captureLock(captureMutex);
4903 captureResult = std::make_optional<status_t>(EAGAIN);
4904 captureCondition.notify_one();
4905 return;
4906 }
4907
4908 status_t result = NO_ERROR;
4909 int fd = -1;
4910 {
4911 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07004912 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08004913 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4914 useIdentityTransform, forSystem, &fd);
4915 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004916 }
4917
4918 {
4919 std::unique_lock<std::mutex> captureLock(captureMutex);
4920 syncFd = fd;
4921 captureResult = std::make_optional<status_t>(result);
4922 captureCondition.notify_one();
4923 }
4924 });
4925
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004926 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004927 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004928 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004929 while (*captureResult == EAGAIN) {
4930 captureResult.reset();
4931 result = postMessageAsync(message);
4932 if (result != NO_ERROR) {
4933 return result;
4934 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07004935 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004936 }
4937 result = *captureResult;
4938 }
4939
4940 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004941 sync_wait(syncFd, -1);
4942 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004943 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004944
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004945 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004946}
4947
chaviwa76b2712017-09-20 12:02:26 -07004948void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4949 TraverseLayersFunction traverseLayers, bool yswap,
4950 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004951 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004952
Lloyd Pique144e1162017-12-20 16:44:52 -08004953 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004954
4955 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004956 const auto raWidth = renderArea.getWidth();
4957 const auto raHeight = renderArea.getHeight();
4958
4959 const auto reqWidth = renderArea.getReqWidth();
4960 const auto reqHeight = renderArea.getReqHeight();
4961 Rect sourceCrop = renderArea.getSourceCrop();
4962
Iris Chang7501ed62018-04-30 14:45:42 +08004963 bool filtering = false;
4964 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4965 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
4966 static_cast<int32_t>(reqHeight) != raWidth;
4967 } else {
4968 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4969 static_cast<int32_t>(reqHeight) != raHeight;
4970 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004971
Dan Stozac1879002014-05-22 15:59:05 -07004972 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004973 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004974 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004975 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08004976 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4977 Transform tr;
4978 uint32_t flags = 0x00;
4979 switch (mPrimaryDisplayOrientation) {
4980 case DisplayState::eOrientation90:
4981 flags = Transform::ROT_90;
4982 break;
4983 case DisplayState::eOrientation180:
4984 flags = Transform::ROT_180;
4985 break;
4986 case DisplayState::eOrientation270:
4987 flags = Transform::ROT_270;
4988 break;
4989 }
4990 tr.set(flags, raWidth, raHeight);
4991 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07004992 }
4993
4994 // ensure that sourceCrop is inside screen
4995 if (sourceCrop.left < 0) {
4996 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4997 }
chaviwa76b2712017-09-20 12:02:26 -07004998 if (sourceCrop.right > raWidth) {
4999 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005000 }
5001 if (sourceCrop.top < 0) {
5002 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5003 }
chaviwa76b2712017-09-20 12:02:26 -07005004 if (sourceCrop.bottom > raHeight) {
5005 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005006 }
5007
Chia-I Wu36574d92018-05-16 10:54:36 -07005008 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5009 engine.setOutputDataSpace(Dataspace::SRGB);
5010 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005011
Mathias Agopian180f10d2013-04-10 22:55:41 -07005012 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005013 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005014
Iris Chang7501ed62018-04-30 14:45:42 +08005015 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5016 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5017 // convert hw orientation into flag presentation
5018 // here inverse transform needed
5019 uint8_t hw_rot_90 = 0x00;
5020 uint8_t hw_flip_hv = 0x00;
5021 switch (mPrimaryDisplayOrientation) {
5022 case DisplayState::eOrientation90:
5023 hw_rot_90 = Transform::ROT_90;
5024 hw_flip_hv = Transform::ROT_180;
5025 break;
5026 case DisplayState::eOrientation180:
5027 hw_flip_hv = Transform::ROT_180;
5028 break;
5029 case DisplayState::eOrientation270:
5030 hw_rot_90 = Transform::ROT_90;
5031 break;
5032 }
5033
5034 // transform flags operation
5035 // 1) flip H V if both have ROT_90 flag
5036 // 2) XOR these flags
5037 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5038 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5039 if (rotation_rot_90 & hw_rot_90) {
5040 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5041 }
5042 rotation = static_cast<Transform::orientation_flags>
5043 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5044 }
5045
Mathias Agopian180f10d2013-04-10 22:55:41 -07005046 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005047 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005048 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005049 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005050
chaviw50da5042018-04-09 13:49:37 -07005051 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005052 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005053 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005054
chaviwa76b2712017-09-20 12:02:26 -07005055 traverseLayers([&](Layer* layer) {
5056 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07005057 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005058 if (filtering) layer->setFiltering(false);
5059 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005060}
5061
chaviwa76b2712017-09-20 12:02:26 -07005062status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5063 TraverseLayersFunction traverseLayers,
5064 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005065 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005066 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005067 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005068 ATRACE_CALL();
5069
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005070 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005071
5072 traverseLayers([&](Layer* layer) {
5073 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5074 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005075
Robert Carr03480e22018-01-04 16:02:06 -08005076 // We allow the system server to take screenshots of secure layers for
5077 // use in situations like the Screen-rotation animation and place
5078 // the impetus on WindowManager to not persist them.
5079 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005080 ALOGW("FB is protected: PERMISSION_DENIED");
5081 return PERMISSION_DENIED;
5082 }
5083
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005084 // this binds the given EGLImage as a framebuffer for the
5085 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005086 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005087 if (bufferBond.getStatus() != NO_ERROR) {
5088 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005089 return INVALID_OPERATION;
5090 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005091
Dan Stozaabcda352017-06-01 14:37:39 -07005092 // this will in fact render into our dequeued buffer
5093 // via an FBO, which means we didn't have to create
5094 // an EGLSurface and therefore we're not
5095 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005096 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005097
Dan Stozaabcda352017-06-01 14:37:39 -07005098 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005099 getRenderEngine().finish();
5100 *outSyncFd = -1;
5101
chaviwa76b2712017-09-20 12:02:26 -07005102 const auto reqWidth = renderArea.getReqWidth();
5103 const auto reqHeight = renderArea.getReqHeight();
5104
Dan Stozaabcda352017-06-01 14:37:39 -07005105 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5106 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005107 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005108 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005109 } else {
5110 base::unique_fd syncFd = getRenderEngine().flush();
5111 if (syncFd < 0) {
5112 getRenderEngine().finish();
5113 }
5114 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005115 }
5116
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005117 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005118}
5119
Mathias Agopiand5556842013-09-19 17:08:37 -07005120void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005121 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005122 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005123 for (size_t y = 0; y < h; y++) {
5124 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5125 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005126 if (p[x] != 0xFF000000) return;
5127 }
5128 }
chaviwa76b2712017-09-20 12:02:26 -07005129 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005130
Robert Carr2047fae2016-11-28 14:09:09 -08005131 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005132 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005133 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005134 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5135 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5136 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5137 static_cast<float>(state.color.a));
5138 i++;
5139 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005140 }
5141}
5142
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005143// ---------------------------------------------------------------------------
5144
Dan Stoza412903f2017-04-27 13:42:17 -07005145void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5146 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005147}
5148
Dan Stoza412903f2017-04-27 13:42:17 -07005149void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5150 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005151}
5152
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005153void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5154 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005155 const LayerVector::Visitor& visitor) {
5156 // We loop through the first level of layers without traversing,
5157 // as we need to interpret min/max layer Z in the top level Z space.
5158 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005159 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005160 continue;
5161 }
5162 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005163 // relative layers are traversed in Layer::traverseInZOrder
5164 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005165 continue;
5166 }
5167 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005168 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005169 return;
5170 }
chaviwa76b2712017-09-20 12:02:26 -07005171 if (!layer->isVisible()) {
5172 return;
5173 }
5174 visitor(layer);
5175 });
5176 }
5177}
5178
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005179}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005180
Chia-I Wu30505fb2018-03-26 16:20:31 -07005181
Mathias Agopian3f844832013-08-07 21:24:32 -07005182#if defined(__gl_h_)
5183#error "don't include gl/gl.h in this file"
5184#endif
5185
5186#if defined(__gl2_h_)
5187#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005188#endif