blob: f21c4630a8dba4251182837504929d5907e504e7 [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
Dan Stoza84d619e2018-03-28 17:07:36 -0700335 property_get("debug.sf.early_phase_offset_ns", value, "0");
336 const int earlyWakeupOffsetOffsetNs = atoi(value);
337 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
338 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
339 sfVsyncPhaseOffsetNs);
340
Romain Guy11d63f42017-07-20 12:47:14 -0700341 // We should be reading 'persist.sys.sf.color_saturation' here
342 // but since /data may be encrypted, we need to wait until after vold
343 // comes online to attempt to read the property. The property is
344 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800345
346 if (useTrebleTestingOverride()) {
347 // Without the override SurfaceFlinger cannot connect to HIDL
348 // services that are not listed in the manifests. Considered
349 // deriving the setting from the set service name, but it
350 // would be brittle if the name that's not 'default' is used
351 // for production purposes later on.
352 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354}
355
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800356void SurfaceFlinger::onFirstRef()
357{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800358 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800359}
360
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800361SurfaceFlinger::~SurfaceFlinger()
362{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800363}
364
Dan Stozac7014012014-02-14 15:03:43 -0800365void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800366{
367 // the window manager died on us. prepare its eulogy.
368
Andy McFadden13a082e2012-08-24 10:16:42 -0700369 // restore initial conditions (default device unblank, etc)
370 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800371
372 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700373 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800374}
375
Robert Carr1db73f62016-12-21 12:58:51 -0800376static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700377 status_t err = client->initCheck();
378 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800379 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380 }
Robert Carr1db73f62016-12-21 12:58:51 -0800381 return nullptr;
382}
383
384sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
385 return initClient(new Client(this));
386}
387
388sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
389 const sp<IGraphicBufferProducer>& gbp) {
390 if (authenticateSurfaceTexture(gbp) == false) {
391 return nullptr;
392 }
393 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
394 if (layer == nullptr) {
395 return nullptr;
396 }
397
398 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800399}
400
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700401sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
402 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700403{
404 class DisplayToken : public BBinder {
405 sp<SurfaceFlinger> flinger;
406 virtual ~DisplayToken() {
407 // no more references, this display must be terminated
408 Mutex::Autolock _l(flinger->mStateLock);
409 flinger->mCurrentState.displays.removeItem(this);
410 flinger->setTransactionFlags(eDisplayTransactionNeeded);
411 }
412 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700413 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700414 : flinger(flinger) {
415 }
416 };
417
418 sp<BBinder> token = new DisplayToken(this);
419
420 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700421 DisplayDeviceState info;
422 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700423 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700424 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700425 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800426 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700427 return token;
428}
429
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700430void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700431 Mutex::Autolock _l(mStateLock);
432
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700433 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700434 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700435 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700436 return;
437 }
438
439 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700440 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700441 ALOGE("destroyDisplay called for non-virtual display");
442 return;
443 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700444 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700445 mCurrentState.displays.removeItemsAt(idx);
446 setTransactionFlags(eDisplayTransactionNeeded);
447}
448
Mathias Agopiane57f2922012-08-09 16:29:12 -0700449sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700450 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700451 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800452 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700453 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700454 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700455}
456
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800457void SurfaceFlinger::bootFinished()
458{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700459 if (mStartPropertySetThread->join() != NO_ERROR) {
460 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800461 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800462 const nsecs_t now = systemTime();
463 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000464 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700465
466 // wait patiently for the window manager death
467 const String16 name("window");
468 sp<IBinder> window(defaultServiceManager()->getService(name));
469 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700470 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700471 }
472
Steven Thomas050b2c82017-03-06 11:45:16 -0800473 if (mVrFlinger) {
474 mVrFlinger->OnBootFinished();
475 }
476
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700477 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700478 // formerly we would just kill the process, but we now ask it to exit so it
479 // can choose where to stop the animation.
480 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700481
482 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
483 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
484 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700485
Dominik Laskowski8c001672018-05-30 16:52:06 -0700486 postMessageAsync(new LambdaMessage([this] { readPersistentProperties(); }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800487}
488
Mathias Agopian3f844832013-08-07 21:24:32 -0700489void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700490 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700491}
492
Lloyd Piquee83f9312018-02-01 12:53:17 -0800493class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700494public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700495 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000496 const char* name) :
497 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700498 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700499 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000500 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
501 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700502 mDispSync(dispSync),
503 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700504 mVsyncMutex(),
505 mPhaseOffset(phaseOffset),
506 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700507
Lloyd Piquee83f9312018-02-01 12:53:17 -0800508 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700509
Lloyd Piquee83f9312018-02-01 12:53:17 -0800510 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700511 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000513 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700514 static_cast<DispSync::Callback*>(this));
515 if (err != NO_ERROR) {
516 ALOGE("error registering vsync callback: %s (%d)",
517 strerror(-err), err);
518 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700519 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700520 } else {
521 status_t err = mDispSync->removeEventListener(
522 static_cast<DispSync::Callback*>(this));
523 if (err != NO_ERROR) {
524 ALOGE("error unregistering vsync callback: %s (%d)",
525 strerror(-err), err);
526 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700527 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700528 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700529 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530 }
531
Lloyd Piquee83f9312018-02-01 12:53:17 -0800532 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534 mCallback = callback;
535 }
536
Lloyd Piquee83f9312018-02-01 12:53:17 -0800537 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700538 Mutex::Autolock lock(mVsyncMutex);
539
540 // Normalize phaseOffset to [0, period)
541 auto period = mDispSync->getPeriod();
542 phaseOffset %= period;
543 if (phaseOffset < 0) {
544 // If we're here, then phaseOffset is in (-period, 0). After this
545 // operation, it will be in (0, period)
546 phaseOffset += period;
547 }
548 mPhaseOffset = phaseOffset;
549
550 // If we're not enabled, we don't need to mess with the listeners
551 if (!mEnabled) {
552 return;
553 }
554
Dan Stoza84d619e2018-03-28 17:07:36 -0700555 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
556 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700557 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700558 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700559 strerror(-err), err);
560 }
561 }
562
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700563private:
564 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800565 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700566 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700567 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568 callback = mCallback;
569
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700570 if (mTraceVsync) {
571 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700572 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700573 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574 }
575
Peiyong Lin566a3b42018-01-09 18:22:43 -0800576 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577 callback->onVSyncEvent(when);
578 }
579 }
580
Tim Murray4a4e4a22016-04-19 16:29:23 +0000581 const char* const mName;
582
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700583 int mValue;
584
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700585 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700586 const String8 mVsyncOnLabel;
587 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700588
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700590
591 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800592 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700593
594 Mutex mVsyncMutex; // Protects the following
595 nsecs_t mPhaseOffset;
596 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700597};
598
Lloyd Piquee83f9312018-02-01 12:53:17 -0800599class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700600public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800601 InjectVSyncSource() = default;
602 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700603
Lloyd Piquee83f9312018-02-01 12:53:17 -0800604 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700605 std::lock_guard<std::mutex> lock(mCallbackMutex);
606 mCallback = callback;
607 }
608
Lloyd Piquee83f9312018-02-01 12:53:17 -0800609 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700610 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700611 if (mCallback) {
612 mCallback->onVSyncEvent(when);
613 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700614 }
615
Lloyd Piquee83f9312018-02-01 12:53:17 -0800616 void setVSyncEnabled(bool) override {}
617 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700618
619private:
620 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800621 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700622};
623
Wei Wangf9b05ee2017-07-19 20:59:39 -0700624// Do not call property_set on main thread which will be blocked by init
625// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700626void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700627 ALOGI( "SurfaceFlinger's main thread ready to run. "
628 "Initializing graphics H/W...");
629
Thierry Strudel2924d012017-08-14 15:19:37 -0700630 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900631
Steven Thomasb02664d2017-07-26 18:48:28 -0700632 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800633
Steven Thomasb02664d2017-07-26 18:48:28 -0700634 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800635 mEventThreadSource =
636 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
637 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800638 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700639 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800640 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800641 "appEventThread");
642 mSfEventThreadSource =
643 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
644 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800645
Lloyd Pique24b0a482018-03-09 18:52:26 -0800646 mSFEventThread =
647 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700648 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800649 [this](nsecs_t timestamp) {
650 mInterceptor->saveVSyncEvent(timestamp);
651 },
652 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800653 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza84d619e2018-03-28 17:07:36 -0700654 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800655
Steven Thomasb02664d2017-07-26 18:48:28 -0700656 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800657 getBE().mRenderEngine =
658 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
659 hasWideColorDisplay
660 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
661 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800662 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700663
664 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
665 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800666 getBE().mHwc.reset(
667 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700668 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800669 // Process any initial hotplug and resulting display changes.
670 processDisplayHotplugEventsLocked();
671 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
672 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800673
Lloyd Piquefcd86612017-12-14 17:15:36 -0800674 // make the default display GLContext current so that we can create textures
675 // when creating Layers (which may happens before we render something)
676 getDefaultDisplayDeviceLocked()->makeCurrent();
677
Steven Thomas050b2c82017-03-06 11:45:16 -0800678 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700679 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700680 // This callback is called from the vr flinger dispatch thread. We
681 // need to call signalTransaction(), which requires holding
682 // mStateLock when we're not on the main thread. Acquiring
683 // mStateLock from the vr flinger dispatch thread might trigger a
684 // deadlock in surface flinger (see b/66916578), so post a message
685 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700686 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700687 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
688 mVrFlingerRequestsDisplay = requestDisplay;
689 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700690 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800691 };
David Sodman105b7dc2017-11-04 20:28:14 -0700692 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
693 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800694 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800695 if (!mVrFlinger) {
696 ALOGE("Failed to start vrflinger");
697 }
698 }
699
Lloyd Pique379adc12018-01-22 17:31:47 -0800700 mEventControlThread = std::make_unique<impl::EventControlThread>(
701 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700702
Mathias Agopian92a979a2012-08-02 18:32:23 -0700703 // initialize our drawing state
704 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700705
Andy McFadden13a082e2012-08-24 10:16:42 -0700706 // set initial conditions (e.g. unblank default device)
707 initializeDisplays();
708
David Sodmanbc815282017-11-05 18:57:52 -0800709 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700710
Wei Wangf9b05ee2017-07-19 20:59:39 -0700711 // Inform native graphics APIs whether the present timestamp is supported:
712 if (getHwComposer().hasCapability(
713 HWC2::Capability::PresentFenceIsNotReliable)) {
714 mStartPropertySetThread = new StartPropertySetThread(false);
715 } else {
716 mStartPropertySetThread = new StartPropertySetThread(true);
717 }
718
719 if (mStartPropertySetThread->Start() != NO_ERROR) {
720 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800721 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800722
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800723 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
724 Dataspace::SRGB_LINEAR);
725
Dan Stoza9e56aa02015-11-02 13:00:03 -0800726 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700727}
728
Romain Guy11d63f42017-07-20 12:47:14 -0700729void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700730 Mutex::Autolock _l(mStateLock);
731
Romain Guy11d63f42017-07-20 12:47:14 -0700732 char value[PROPERTY_VALUE_MAX];
733
734 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800735 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700736 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800737 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100738
739 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700740 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700741}
742
Mathias Agopiana67e4182012-06-19 17:26:12 -0700743void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800744 // Start boot animation service by setting a property mailbox
745 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700746 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800747 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700748 if (mStartPropertySetThread->join() != NO_ERROR) {
749 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800750 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700751}
752
Mathias Agopian875d8e12013-06-07 15:35:48 -0700753size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800754 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700755}
756
Mathias Agopian875d8e12013-06-07 15:35:48 -0700757size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800758 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700759}
760
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800761// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800762
Jamie Gennis582270d2011-08-17 18:19:00 -0700763bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800764 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800765 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800766 return authenticateSurfaceTextureLocked(bufferProducer);
767}
768
769bool SurfaceFlinger::authenticateSurfaceTextureLocked(
770 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800771 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800772 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800773}
774
Brian Anderson6b376712017-04-04 10:51:39 -0700775status_t SurfaceFlinger::getSupportedFrameTimestamps(
776 std::vector<FrameEvent>* outSupported) const {
777 *outSupported = {
778 FrameEvent::REQUESTED_PRESENT,
779 FrameEvent::ACQUIRE,
780 FrameEvent::LATCH,
781 FrameEvent::FIRST_REFRESH_START,
782 FrameEvent::LAST_REFRESH_START,
783 FrameEvent::GPU_COMPOSITION_DONE,
784 FrameEvent::DEQUEUE_READY,
785 FrameEvent::RELEASE,
786 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700787 ConditionalLock _l(mStateLock,
788 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700789 if (!getHwComposer().hasCapability(
790 HWC2::Capability::PresentFenceIsNotReliable)) {
791 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
792 }
793 return NO_ERROR;
794}
795
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700796status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
797 Vector<DisplayInfo>* configs) {
798 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700799 return BAD_VALUE;
800 }
801
Jesse Hall692c7232012-11-08 15:41:56 -0800802 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700803 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
804 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700805 type = i;
806 break;
807 }
808 }
809
810 if (type < 0) {
811 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700812 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700813
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814 // TODO: Not sure if display density should handled by SF any longer
815 class Density {
816 static int getDensityFromProperty(char const* propName) {
817 char property[PROPERTY_VALUE_MAX];
818 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800819 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 density = atoi(property);
821 }
822 return density;
823 }
824 public:
825 static int getEmuDensity() {
826 return getDensityFromProperty("qemu.sf.lcd_density"); }
827 static int getBuildDensity() {
828 return getDensityFromProperty("ro.sf.lcd_density"); }
829 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700830
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700832
Steven Thomas6d8110b2017-08-31 18:24:21 -0700833 ConditionalLock _l(mStateLock,
834 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800835 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 DisplayInfo info = DisplayInfo();
837
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838 float xdpi = hwConfig->getDpiX();
839 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700840
841 if (type == DisplayDevice::DISPLAY_PRIMARY) {
842 // The density of the device is provided by a build property
843 float density = Density::getBuildDensity() / 160.0f;
844 if (density == 0) {
845 // the build doesn't provide a density -- this is wrong!
846 // use xdpi instead
847 ALOGE("ro.sf.lcd_density must be defined as a build property");
848 density = xdpi / 160.0f;
849 }
850 if (Density::getEmuDensity()) {
851 // if "qemu.sf.lcd_density" is specified, it overrides everything
852 xdpi = ydpi = density = Density::getEmuDensity();
853 density /= 160.0f;
854 }
855 info.density = density;
856
857 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700858 const auto display = getDefaultDisplayDeviceLocked();
859 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 } else {
861 // TODO: where should this value come from?
862 static const int TV_DENSITY = 213;
863 info.density = TV_DENSITY / 160.0f;
864 info.orientation = 0;
865 }
866
Dan Stoza9e56aa02015-11-02 13:00:03 -0800867 info.w = hwConfig->getWidth();
868 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 info.xdpi = xdpi;
870 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900872 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873
Andy McFadden91b2ca82014-06-13 14:04:23 -0700874 // This is how far in advance a buffer must be queued for
875 // presentation at a given time. If you want a buffer to appear
876 // on the screen at time N, you must submit the buffer before
877 // (N - presentationDeadline).
878 //
879 // Normally it's one full refresh period (to give SF a chance to
880 // latch the buffer), but this can be reduced by configuring a
881 // DispSync offset. Any additional delays introduced by the hardware
882 // composer or panel must be accounted for here.
883 //
884 // We add an additional 1ms to allow for processing time and
885 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800887 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700888
889 // All non-virtual displays are currently considered secure.
890 info.secure = true;
891
Iris Chang7501ed62018-04-30 14:45:42 +0800892 if (type == DisplayDevice::DISPLAY_PRIMARY &&
893 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
894 std::swap(info.w, info.h);
895 }
896
Michael Wright28f24d02016-07-12 13:30:53 -0700897 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700898 }
899
Dan Stoza7f7da322014-05-02 15:26:25 -0700900 return NO_ERROR;
901}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700902
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700903status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
904 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700905 return BAD_VALUE;
906 }
907
908 // FIXME for now we always return stats for the primary display
909 memset(stats, 0, sizeof(*stats));
910 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
911 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
912 return NO_ERROR;
913}
914
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700915int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
916 const auto display = getDisplayDevice(displayToken);
917 if (!display) {
918 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800919 return BAD_VALUE;
920 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700923}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700924
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700925void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
926 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700927 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700928 return;
929 }
930
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700931 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700932 ALOGW("Trying to set config for virtual display");
933 return;
934 }
935
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700936 display->setActiveConfig(mode);
937 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700938}
939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700941 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700942 Vector<DisplayInfo> configs;
943 getDisplayConfigs(displayToken, &configs);
944 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
945 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
946 configs.size());
947 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700948 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949 const auto display = getDisplayDevice(displayToken);
950 if (!display) {
951 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
952 displayToken.get());
953 } else if (display->isVirtual()) {
954 ALOGW("Attempt to set active config %d for virtual display", mode);
955 } else {
956 setActiveConfigInternal(display, mode);
957 }
958 }));
959
Mathias Agopian888c8222012-08-04 21:10:38 -0700960 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700961}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
963 Vector<ColorMode>* outColorModes) {
964 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700965 return BAD_VALUE;
966 }
967
Michael Wright28f24d02016-07-12 13:30:53 -0700968 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700969 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
970 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700971 type = i;
972 break;
973 }
974 }
975
976 if (type < 0) {
977 return type;
978 }
979
Peiyong Lina52f0292018-03-14 17:26:31 -0700980 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700981 {
982 ConditionalLock _l(mStateLock,
983 std::this_thread::get_id() != mMainThreadId);
984 modes = getHwComposer().getColorModes(type);
985 }
Michael Wright28f24d02016-07-12 13:30:53 -0700986 outColorModes->clear();
987 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
988
989 return NO_ERROR;
990}
991
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700992ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
993 if (const auto display = getDisplayDevice(displayToken)) {
994 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700995 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700996 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700997}
998
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700999void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1000 Dataspace dataSpace, RenderIntent renderIntent) {
1001 ColorMode currentMode = display->getActiveColorMode();
1002 Dataspace currentDataSpace = display->getCompositionDataSpace();
1003 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001004
Peiyong Lin38e9a562018-04-10 16:24:20 -07001005 if (mode == currentMode && dataSpace == currentDataSpace &&
1006 renderIntent == currentRenderIntent) {
1007 return;
1008 }
1009
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001010 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001011 ALOGW("Trying to set config for virtual display");
1012 return;
1013 }
1014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001015 display->setActiveColorMode(mode);
1016 display->setCompositionDataSpace(dataSpace);
1017 display->setActiveRenderIntent(renderIntent);
1018 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001019
1020 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001021 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1022 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001023}
1024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001026 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001027 Vector<ColorMode> modes;
1028 getDisplayColorModes(displayToken, &modes);
1029 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1030 if (mode < ColorMode::NATIVE || !exists) {
1031 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1032 decodeColorMode(mode).c_str(), mode, displayToken.get());
1033 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001034 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001035 const auto display = getDisplayDevice(displayToken);
1036 if (!display) {
1037 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1038 decodeColorMode(mode).c_str(), mode, displayToken.get());
1039 } else if (display->isVirtual()) {
1040 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1041 decodeColorMode(mode).c_str(), mode);
1042 } else {
1043 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1044 RenderIntent::COLORIMETRIC);
1045 }
1046 }));
1047
Michael Wright28f24d02016-07-12 13:30:53 -07001048 return NO_ERROR;
1049}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001050
Svetoslavd85084b2014-03-20 10:28:31 -07001051status_t SurfaceFlinger::clearAnimationFrameStats() {
1052 Mutex::Autolock _l(mStateLock);
1053 mAnimFrameTracker.clearStats();
1054 return NO_ERROR;
1055}
1056
1057status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1058 Mutex::Autolock _l(mStateLock);
1059 mAnimFrameTracker.getStats(outStats);
1060 return NO_ERROR;
1061}
1062
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001063status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1064 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001065 Mutex::Autolock _l(mStateLock);
1066
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001067 const auto display = getDisplayDeviceLocked(displayToken);
1068 if (!display) {
1069 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001070 return BAD_VALUE;
1071 }
1072
Peiyong Linfb069302018-04-25 14:34:31 -07001073 // At this point the DisplayDeivce should already be set up,
1074 // meaning the luminance information is already queried from
1075 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001076 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001077 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1078 capabilities.getDesiredMaxLuminance(),
1079 capabilities.getDesiredMaxAverageLuminance(),
1080 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001081
1082 return NO_ERROR;
1083}
1084
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001085status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001086 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001087 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001088
Chia-I Wu90f669f2017-10-05 14:24:41 -07001089 if (mInjectVSyncs == enable) {
1090 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001091 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001092
1093 if (enable) {
1094 ALOGV("VSync Injections enabled");
1095 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001096 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001097 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001098 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001099 impl::EventThread::InterceptVSyncsCallback(),
1100 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001101 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001102 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001103 } else {
1104 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001105 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001106 }
1107
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001108 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001109 }));
1110
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001111 return NO_ERROR;
1112}
1113
1114status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 Mutex::Autolock _l(mStateLock);
1116
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001117 if (!mInjectVSyncs) {
1118 ALOGE("VSync Injections not enabled");
1119 return BAD_VALUE;
1120 }
1121 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1122 ALOGV("Injecting VSync inside SurfaceFlinger");
1123 mVSyncInjector->onInjectSyncEvent(when);
1124 }
1125 return NO_ERROR;
1126}
1127
Lloyd Pique755e3192018-01-31 16:46:15 -08001128status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1129 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001130 IPCThreadState* ipc = IPCThreadState::self();
1131 const int pid = ipc->getCallingPid();
1132 const int uid = ipc->getCallingUid();
1133 if ((uid != AID_SHELL) &&
1134 !PermissionCache::checkPermission(sDump, pid, uid)) {
1135 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1136 return PERMISSION_DENIED;
1137 }
1138
1139 // Try to acquire a lock for 1s, fail gracefully
1140 const status_t err = mStateLock.timedLock(s2ns(1));
1141 const bool locked = (err == NO_ERROR);
1142 if (!locked) {
1143 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1144 return TIMED_OUT;
1145 }
1146
1147 outLayers->clear();
1148 mCurrentState.traverseInZOrder([&](Layer* layer) {
1149 outLayers->push_back(layer->getLayerDebugInfo());
1150 });
1151
1152 mStateLock.unlock();
1153 return NO_ERROR;
1154}
1155
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001156// ----------------------------------------------------------------------------
1157
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001158sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1159 ISurfaceComposer::VsyncSource vsyncSource) {
1160 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1161 return mSFEventThread->createEventConnection();
1162 } else {
1163 return mEventThread->createEventConnection();
1164 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001165}
1166
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001167// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001168
1169void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001170 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001171}
1172
1173void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001174 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001175}
1176
1177void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001178 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001179}
1180
1181void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001182 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001183 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001184}
1185
1186status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001187 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001188 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001189}
1190
1191status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001192 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001193 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001194 if (res == NO_ERROR) {
1195 msg->wait();
1196 }
1197 return res;
1198}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001199
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001200void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001201 do {
1202 waitForEvent();
1203 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001204}
1205
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001206void SurfaceFlinger::enableHardwareVsync() {
1207 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001208 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001209 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001210 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1211 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001212 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001213 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001214}
1215
Jesse Hall948fe0c2013-10-14 12:56:09 -07001216void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001217 Mutex::Autolock _l(mHWVsyncLock);
1218
Jesse Hall948fe0c2013-10-14 12:56:09 -07001219 if (makeAvailable) {
1220 mHWVsyncAvailable = true;
1221 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001222 // Hardware vsync is not currently available, so abort the resync
1223 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001224 return;
1225 }
1226
David Sodman105b7dc2017-11-04 20:28:14 -07001227 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001228 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001229
1230 mPrimaryDispSync.reset();
1231 mPrimaryDispSync.setPeriod(period);
1232
1233 if (!mPrimaryHWVsyncEnabled) {
1234 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001235 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1236 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001237 mPrimaryHWVsyncEnabled = true;
1238 }
1239}
1240
Jesse Hall948fe0c2013-10-14 12:56:09 -07001241void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001242 Mutex::Autolock _l(mHWVsyncLock);
1243 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001244 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1245 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246 mPrimaryDispSync.endResync();
1247 mPrimaryHWVsyncEnabled = false;
1248 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001249 if (makeUnavailable) {
1250 mHWVsyncAvailable = false;
1251 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001252}
1253
Tim Murray4a4e4a22016-04-19 16:29:23 +00001254void SurfaceFlinger::resyncWithRateLimit() {
1255 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001256
1257 // No explicit locking is needed here since EventThread holds a lock while calling this method
1258 static nsecs_t sLastResyncAttempted = 0;
1259 const nsecs_t now = systemTime();
1260 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001261 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001262 }
Dan Stoza57164302017-05-08 14:03:54 -07001263 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001264}
1265
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001266void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1267 int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001268 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001269 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001270 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001271 return;
1272 }
1273
1274 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001275 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001276 return;
1277 }
1278
Jamie Gennisd1700752013-10-14 12:22:52 -07001279 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001280
Jamie Gennisd1700752013-10-14 12:22:52 -07001281 { // Scope for the lock
1282 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001283 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001284 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001285 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001286 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001287
1288 if (needsHwVsync) {
1289 enableHardwareVsync();
1290 } else {
1291 disableHardwareVsync(false);
1292 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001293}
1294
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001295void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001296 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1297 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001298}
1299
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001300void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001301 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001302 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001303 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001304
Lloyd Piqueba04e622017-12-14 17:11:26 -08001305 // Ignore events that do not have the right sequenceId.
1306 if (sequenceId != getBE().mComposerSequenceId) {
1307 return;
1308 }
1309
Steven Thomasb02664d2017-07-26 18:48:28 -07001310 // Only lock if we're not on the main thread. This function is normally
1311 // called on a hwbinder thread, but for the primary display it's called on
1312 // the main thread with the state lock already held, so don't attempt to
1313 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001314 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001315
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001316 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001317
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001318 if (std::this_thread::get_id() == mMainThreadId) {
1319 // Process all pending hot plug events immediately if we are on the main thread.
1320 processDisplayHotplugEventsLocked();
1321 }
1322
Lloyd Piqueba04e622017-12-14 17:11:26 -08001323 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001324}
1325
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001326void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001327 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001328 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001329 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001330 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001331 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001332}
1333
Dan Stoza9e56aa02015-11-02 13:00:03 -08001334void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001335 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001336 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001337 getHwComposer().setVsyncEnabled(disp,
1338 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001339}
1340
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001341// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001342void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001343 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001344 // Clear the drawing state so that the logic inside of
1345 // handleTransactionLocked will fire. It will determine the delta between
1346 // mCurrentState and mDrawingState and re-apply all changes when we make the
1347 // transition.
1348 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001349 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001350 mDisplays.clear();
1351}
1352
Steven Thomas050b2c82017-03-06 11:45:16 -08001353void SurfaceFlinger::updateVrFlinger() {
1354 if (!mVrFlinger)
1355 return;
1356 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001357 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001358 return;
1359 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001360
David Sodman105b7dc2017-11-04 20:28:14 -07001361 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 ALOGE("Vr flinger is only supported for remote hardware composer"
1363 " service connections. Ignoring request to transition to vr"
1364 " flinger.");
1365 mVrFlingerRequestsDisplay = false;
1366 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001367 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001368
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001369 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001370
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001371 int currentDisplayPowerMode = getDefaultDisplayDeviceLocked()->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001372
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001374 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001376
Steven Thomasb02664d2017-07-26 18:48:28 -07001377 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001378 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001379 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1380 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001381 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001382
David Sodman105b7dc2017-11-04 20:28:14 -07001383 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1384 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001385
1386 if (vrFlingerRequestsDisplay) {
1387 mVrFlinger->GrantDisplayOwnership();
1388 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001389 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001390 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001391
1392 mVisibleRegionsDirty = true;
1393 invalidateHwcGeometry();
1394
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001395 // Re-enable default display.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001396 setPowerModeInternal(getDefaultDisplayDeviceLocked(), currentDisplayPowerMode,
1397 /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001398
Steven Thomasb02664d2017-07-26 18:48:28 -07001399 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001400 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001401 const nsecs_t period = activeConfig->getVsyncPeriod();
1402 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001403
Steven Thomasb02664d2017-07-26 18:48:28 -07001404 // Use phase of 0 since phase is not known.
1405 // Use latency of 0, which will snap to the ideal latency.
1406 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001407
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001408 android_atomic_or(1, &mRepaintEverything);
1409 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001410}
1411
Mathias Agopian4fec8732012-06-29 14:12:52 -07001412void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001413 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001414 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001415 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001416 bool frameMissed = !mHadClientComposition &&
1417 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001418 (mPreviousPresentFence->getSignalTime() ==
1419 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001420 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001421 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001422 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001423 mTimeStats.incrementMissedFrames();
1424 if (mPropagateBackpressure) {
1425 signalLayerUpdate();
1426 break;
1427 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001428 }
Dan Stoza50182882016-07-08 12:02:20 -07001429
Steven Thomas050b2c82017-03-06 11:45:16 -08001430 // Now that we're going to make it to the handleMessageTransaction()
1431 // call below it's safe to call updateVrFlinger(), which will
1432 // potentially trigger a display handoff.
1433 updateVrFlinger();
1434
Dan Stoza6b9454d2014-11-07 16:00:59 -08001435 bool refreshNeeded = handleMessageTransaction();
1436 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001437 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001438 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001439 // Signal a refresh if a transaction modified the window state,
1440 // a new buffer was latched, or if HWC has requested a full
1441 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001442 signalRefresh();
1443 }
1444 break;
1445 }
1446 case MessageQueue::REFRESH: {
1447 handleMessageRefresh();
1448 break;
1449 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001450 }
1451}
1452
Dan Stoza6b9454d2014-11-07 16:00:59 -08001453bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001454 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001455 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001456 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001457 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001458 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001459 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001460}
1461
Dan Stoza6b9454d2014-11-07 16:00:59 -08001462bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001463 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001464 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001465}
1466
1467void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001468 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001469
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001470 mRefreshPending = false;
1471
Chia-I Wu30505fb2018-03-26 16:20:31 -07001472 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001473
Chia-I Wu30505fb2018-03-26 16:20:31 -07001474 preComposition(refreshStartTime);
1475 rebuildLayerStacks();
1476 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001477 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001478 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001479 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001480 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001481 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001482
David Sodman105b7dc2017-11-04 20:28:14 -07001483 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001484
1485 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001486 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001487 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001488 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001489 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001490 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001491
Dan Stoza9e56aa02015-11-02 13:00:03 -08001492 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001493}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001494
Mathias Agopiancd60f992012-08-16 16:28:27 -07001495void SurfaceFlinger::doDebugFlashRegions()
1496{
1497 // is debugging enabled
1498 if (CC_LIKELY(!mDebugRegion))
1499 return;
1500
1501 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001502 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001503 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001504 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001505 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001506 if (!dirtyRegion.isEmpty()) {
1507 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001508 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001509
1510 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001511 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001512 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001513 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1514
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001515 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001516 }
1517 }
1518 }
1519
1520 postFramebuffer();
1521
1522 if (mDebugRegion > 1) {
1523 usleep(mDebugRegion * 1000);
1524 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001525
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001526 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001527 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001528 continue;
1529 }
1530
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001531 status_t result = display->prepareFrame(*getBE().mHwc);
1532 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001533 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001534 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001535}
1536
Adrian Roos1e1a1282017-11-01 19:05:31 +01001537void SurfaceFlinger::doTracing(const char* where) {
1538 ATRACE_CALL();
1539 ATRACE_NAME(where);
1540 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001541 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001542 }
1543}
1544
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001545void SurfaceFlinger::logLayerStats() {
1546 ATRACE_CALL();
1547 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001548 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001549 if (display->isPrimary()) {
1550 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001551 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001552 }
1553 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001554
1555 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001556 }
1557}
1558
Chia-I Wu30505fb2018-03-26 16:20:31 -07001559void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001561 ATRACE_CALL();
1562 ALOGV("preComposition");
1563
Mathias Agopiancd60f992012-08-16 16:28:27 -07001564 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001565 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001566 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001567 needExtraInvalidate = true;
1568 }
Robert Carr2047fae2016-11-28 14:09:09 -08001569 });
1570
Mathias Agopiancd60f992012-08-16 16:28:27 -07001571 if (needExtraInvalidate) {
1572 signalLayerUpdate();
1573 }
1574}
1575
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001576void SurfaceFlinger::updateCompositorTiming(
1577 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1578 std::shared_ptr<FenceTime>& presentFenceTime) {
1579 // Update queue of past composite+present times and determine the
1580 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001581 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001582 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001583 while (!getBE().mCompositePresentTimes.empty()) {
1584 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001585 // Cached values should have been updated before calling this method,
1586 // which helps avoid duplicate syscalls.
1587 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1588 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1589 break;
1590 }
1591 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001592 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001593 }
1594
1595 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001596 while (getBE().mCompositePresentTimes.size() > 16) {
1597 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001598 }
1599
Brian Andersond0010582017-03-07 13:20:31 -08001600 setCompositorTimingSnapped(
1601 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1602}
1603
1604void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1605 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001606 // Integer division and modulo round toward 0 not -inf, so we need to
1607 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001608 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001609 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1610 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1611
Brian Andersond0010582017-03-07 13:20:31 -08001612 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1613 if (idealLatency <= 0) {
1614 idealLatency = vsyncInterval;
1615 }
1616
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001617 // Snap the latency to a value that removes scheduling jitter from the
1618 // composition and present times, which often have >1ms of jitter.
1619 // Reducing jitter is important if an app attempts to extrapolate
1620 // something (such as user input) to an accurate diasplay time.
1621 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1622 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001623 nsecs_t bias = vsyncInterval / 2;
1624 int64_t extraVsyncs =
1625 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1626 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1627 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001628
David Sodman99974d22017-11-28 12:04:33 -08001629 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1630 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1631 getBE().mCompositorTiming.interval = vsyncInterval;
1632 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001633}
1634
Chia-I Wu30505fb2018-03-26 16:20:31 -07001635void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001636{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001637 ATRACE_CALL();
1638 ALOGV("postComposition");
1639
Brian Anderson3546a3f2016-07-14 11:51:14 -07001640 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001641 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001642 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001643 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001644 }
1645
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001646 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001647 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001648
David Sodman73beded2017-11-15 11:56:06 -08001649 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001650 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001651 if (display && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001652 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001653 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001654 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001655 } else {
1656 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1657 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001658
David Sodman73beded2017-11-15 11:56:06 -08001659 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001660 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001661 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001662 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001663
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001664 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1665 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1666
Chia-I Wu30505fb2018-03-26 16:20:31 -07001667 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001668 // when we started doing work for this frame, but that should be okay
1669 // since updateCompositorTiming has snapping logic.
1670 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001671 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001672 CompositorTiming compositorTiming;
1673 {
David Sodman99974d22017-11-28 12:04:33 -08001674 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1675 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001676 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001677
Robert Carr2047fae2016-11-28 14:09:09 -08001678 mDrawingState.traverseInZOrder([&](Layer* layer) {
1679 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001680 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001681 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001682 recordBufferingStats(layer->getName().string(),
1683 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001684 }
Robert Carr2047fae2016-11-28 14:09:09 -08001685 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001686
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001687 if (presentFenceTime->isValid()) {
1688 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001689 enableHardwareVsync();
1690 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001691 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001692 }
1693 }
1694
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001695 if (!hasSyncFramework) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001696 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001697 enableHardwareVsync();
1698 }
1699 }
1700
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001701 if (mAnimCompositionPending) {
1702 mAnimCompositionPending = false;
1703
Brian Anderson4e606e32017-03-16 15:34:57 -07001704 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001705 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001706 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001707 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001708 // The HWC doesn't support present fences, so use the refresh
1709 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001710 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001711 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001712 mAnimFrameTracker.setActualPresentTime(presentTime);
1713 }
1714 mAnimFrameTracker.advanceFrame();
1715 }
Dan Stozab90cf072015-03-05 11:05:59 -08001716
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001717 mTimeStats.incrementTotalFrames();
1718 if (mHadClientComposition) {
1719 mTimeStats.incrementClientCompositionFrames();
1720 }
1721
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001722 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001723 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001724 return;
1725 }
1726
1727 nsecs_t currentTime = systemTime();
1728 if (mHasPoweredOff) {
1729 mHasPoweredOff = false;
1730 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001731 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001732 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001733 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1734 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001735 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001736 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001737 }
David Sodman4a36e932017-11-07 14:29:47 -08001738 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001739 }
David Sodman4a36e932017-11-07 14:29:47 -08001740 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001741}
1742
1743void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001744 ATRACE_CALL();
1745 ALOGV("rebuildLayerStacks");
1746
Mathias Agopiancd60f992012-08-16 16:28:27 -07001747 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001748 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001749 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001750 mVisibleRegionsDirty = false;
1751 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001752
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001753 for (const auto& pair : mDisplays) {
1754 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001755 Region opaqueRegion;
1756 Region dirtyRegion;
1757 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001758 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001759 const Transform& tr = display->getTransform();
1760 const Rect bounds = display->getBounds();
1761 if (display->isPoweredOn()) {
1762 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001763
Jeff Sharkey76488112017-02-27 14:15:18 -07001764 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001765 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001766 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001767 Region drawRegion(tr.transform(
1768 layer->visibleNonTransparentRegion));
1769 drawRegion.andSelf(bounds);
1770 if (!drawRegion.isEmpty()) {
1771 layersSortedByZ.add(layer);
1772 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001773 // Clear out the HWC layer if this layer was
1774 // previously visible, but no longer is
Dominik Laskowski7e045462018-05-30 13:02:02 -07001775 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001776 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001777 } else {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001778 // WM changes display->layerStack upon sleep/awake.
Chia-I Wu30505fb2018-03-26 16:20:31 -07001779 // Here we make sure we delete the HWC layers even if
1780 // WM changed their layer stack.
Dominik Laskowski7e045462018-05-30 13:02:02 -07001781 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001782 }
1783
1784 // If a layer is not going to get a release fence because
1785 // it is invisible, but it is also going to release its
1786 // old buffer, add it to the list of layers needing
1787 // fences.
1788 if (hwcLayerDestroyed) {
1789 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1790 mLayersWithQueuedFrames.cend(), layer);
1791 if (found != mLayersWithQueuedFrames.cend()) {
1792 layersNeedingFences.add(layer);
1793 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001794 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001795 });
1796 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001797 display->setVisibleLayersSortedByZ(layersSortedByZ);
1798 display->setLayersNeedingFences(layersNeedingFences);
1799 display->undefinedRegion.set(bounds);
1800 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1801 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001802 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001803 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001804}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001805
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001806// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001807// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001808// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001809// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001810// The returned HDR data space is one of
1811// - Dataspace::UNKNOWN
1812// - Dataspace::BT2020_HLG
1813// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001814Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1815 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001816 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001817 *outHdrDataSpace = Dataspace::UNKNOWN;
1818
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001819 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001820 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001821 case Dataspace::V0_SCRGB:
1822 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001823 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001824 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001825 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001826 case Dataspace::BT2020_PQ:
1827 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001828 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001829 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001830 case Dataspace::BT2020_HLG:
1831 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001832 // When there's mixed PQ content and HLG content, we set the HDR
1833 // data space to be BT2020_PQ and convert HLG to PQ.
1834 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1835 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001836 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001837 break;
1838 default:
1839 break;
1840 }
Romain Guy54f154a2017-10-24 21:40:32 +01001841 }
1842
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001843 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001844}
1845
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001846// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001847void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1848 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001849 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1850 *outMode = ColorMode::NATIVE;
1851 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001852 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001853 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001854 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001855
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001856 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001857 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001858
Peiyong Lindfde5112018-06-05 10:58:41 -07001859 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001860 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001861 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001862 if (isHdr) {
1863 bestDataSpace = hdrDataSpace;
1864 }
1865
Chia-I Wu0d711262018-05-21 15:19:35 -07001866 RenderIntent intent;
1867 switch (mDisplayColorSetting) {
1868 case DisplayColorSetting::MANAGED:
1869 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001870 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001871 break;
1872 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001873 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001874 break;
1875 default: // vendor display color setting
1876 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1877 break;
1878 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001879
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001880 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001881}
1882
Chia-I Wu30505fb2018-03-26 16:20:31 -07001883void SurfaceFlinger::setUpHWComposer() {
1884 ATRACE_CALL();
1885 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001887 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001888 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
1889 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1890 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07001891
1892 // If nothing has changed (!dirty), don't recompose.
1893 // If something changed, but we don't currently have any visible layers,
1894 // and didn't when we last did a composition, then skip it this time.
1895 // The second rule does two things:
1896 // - When all layers are removed from a display, we'll emit one black
1897 // frame, then nothing more until we get new layers.
1898 // - When a display is created with a private layer stack, we won't
1899 // emit any black frames until a layer is added to the layer stack.
1900 bool mustRecompose = dirty && !(empty && wasEmpty);
1901
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001902 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001903 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
1904 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07001905
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001906 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001907
1908 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001909 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07001910 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001911 }
1912
Chia-I Wu30505fb2018-03-26 16:20:31 -07001913 // build the h/w work list
1914 if (CC_UNLIKELY(mGeometryInvalid)) {
1915 mGeometryInvalid = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001916 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001917 const auto displayId = display->getId();
1918 if (displayId >= 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001919 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001920 for (size_t i = 0; i < currentLayers.size(); i++) {
1921 const auto& layer = currentLayers[i];
Dominik Laskowski7e045462018-05-30 13:02:02 -07001922 if (!layer->hasHwcLayer(displayId)) {
1923 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1924 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001925 continue;
1926 }
1927 }
1928
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001929 layer->setGeometry(display, i);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001930 if (mDebugDisableHWC || mDebugRegion) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001931 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001932 }
1933 }
1934 }
1935 }
1936 }
1937
Chia-I Wu30505fb2018-03-26 16:20:31 -07001938 // Set the per-frame data
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001939 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001940 const auto displayId = display->getId();
1941 if (displayId < 0) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001942 continue;
1943 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07001944
Chia-I Wu28f320b2018-05-03 11:02:56 -07001945 if (mDrawingState.colorMatrixChanged) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001946 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski7e045462018-05-30 13:02:02 -07001947 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001948 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001949 displayId, result);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001950 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001951 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu692e0832018-06-05 15:46:58 -07001952 if (layer->isHdrY410()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001953 layer->forceClientComposition(displayId);
Chia-I Wu692e0832018-06-05 15:46:58 -07001954 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1955 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1956 !display->hasHDR10Support()) {
1957 layer->forceClientComposition(displayId);
1958 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1959 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1960 !display->hasHLGSupport()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001961 layer->forceClientComposition(displayId);
Peiyong Linf59a7192018-04-25 11:19:31 -07001962 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001963
Dominik Laskowski7e045462018-05-30 13:02:02 -07001964 if (layer->getForceClientComposition(displayId)) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001965 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07001966 layer->setCompositionType(displayId, HWC2::Composition::Client);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001967 continue;
1968 }
1969
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001970 layer->setPerFrameData(display);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001971 }
1972
1973 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001974 ColorMode colorMode;
1975 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001976 RenderIntent renderIntent;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001977 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1978 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001979 }
1980 }
1981
Chia-I Wu28f320b2018-05-03 11:02:56 -07001982 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07001983
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001984 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001985 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001986 continue;
1987 }
1988
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001989 status_t result = display->prepareFrame(*getBE().mHwc);
1990 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001991 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001992 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001993}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001994
Mathias Agopiancd60f992012-08-16 16:28:27 -07001995void SurfaceFlinger::doComposition() {
1996 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001997 ALOGV("doComposition");
1998
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001999 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002000 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002001 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002002 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002003 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002004
2005 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002006 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002008 display->dirtyRegion.clear();
2009 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002010 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002011 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002012 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002013}
2014
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002015void SurfaceFlinger::postFramebuffer()
2016{
Mathias Agopian841cde52012-03-01 15:44:37 -08002017 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002019
Mathias Agopiana44b0412011-10-16 18:46:35 -07002020 const nsecs_t now = systemTime();
2021 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002022
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002023 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002024 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002025 continue;
2026 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002027 const auto displayId = display->getId();
2028 if (displayId >= 0) {
2029 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002030 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002031 display->onSwapBuffersCompleted();
2032 display->makeCurrent();
2033 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002034 // The layer buffer from the previous frame (if any) is released
2035 // by HWC only when the release fence from this frame (if any) is
2036 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002037 auto hwcLayer = layer->getHwcLayer(displayId);
2038 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002039
2040 // If the layer was client composited in the previous frame, we
2041 // need to merge with the previous client target acquire fence.
2042 // Since we do not track that, always merge with the current
2043 // client target acquire fence when it is available, even though
2044 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002045 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002046 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002047 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002048 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002049
David Sodmanb8af7922017-12-21 15:17:55 -08002050 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 }
Chia-I Wu83806892017-11-16 10:50:20 -08002052
2053 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002054 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002055 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002056 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002057 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002058 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002059 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002060 }
2061 }
2062
Dominik Laskowski7e045462018-05-30 13:02:02 -07002063 if (displayId >= 0) {
2064 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002065 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002066 }
2067
Mathias Agopiana44b0412011-10-16 18:46:35 -07002068 mLastSwapBufferTime = systemTime() - now;
2069 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002070
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002071 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002072 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2073 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2074 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2075 logFrameStats();
2076 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002077 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002078}
2079
Mathias Agopian87baae12012-07-31 12:38:26 -07002080void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002081{
Mathias Agopian841cde52012-03-01 15:44:37 -08002082 ATRACE_CALL();
2083
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002084 // here we keep a copy of the drawing state (that is the state that's
2085 // going to be overwritten by handleTransactionLocked()) outside of
2086 // mStateLock so that the side-effects of the State assignment
2087 // don't happen with mStateLock held (which can cause deadlocks).
2088 State drawingState(mDrawingState);
2089
Mathias Agopianca4d3602011-05-19 15:38:14 -07002090 Mutex::Autolock _l(mStateLock);
2091 const nsecs_t now = systemTime();
2092 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002093
Mathias Agopianca4d3602011-05-19 15:38:14 -07002094 // Here we're guaranteed that some transaction flags are set
2095 // so we can call handleTransactionLocked() unconditionally.
2096 // We call getTransactionFlags(), which will also clear the flags,
2097 // with mStateLock held to guarantee that mCurrentState won't change
2098 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002099
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002100 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002101 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002102 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002103
Mathias Agopianca4d3602011-05-19 15:38:14 -07002104 mLastTransactionTime = systemTime() - now;
2105 mDebugInTransaction = 0;
2106 invalidateHwcGeometry();
2107 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002108}
2109
Dominik Laskowski7e045462018-05-30 13:02:02 -07002110DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002111 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002112 // Figure out whether the event is for the primary display or an
2113 // external display by matching the Hwc display id against one for a
2114 // connected display. If we did not find a match, we then check what
2115 // displays are not already connected to determine the type. If we don't
2116 // have a connected primary display, we assume the new display is meant to
2117 // be the primary display, and then if we don't have an external display,
2118 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002119 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2120 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002121 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002122 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002123 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002124 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002125 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002126 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002127 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002128 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002129 return DisplayDevice::DISPLAY_EXTERNAL;
2130 }
2131
2132 return DisplayDevice::DISPLAY_ID_INVALID;
2133}
2134
Lloyd Piqueba04e622017-12-14 17:11:26 -08002135void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2136 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002137 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002138 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002139 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002140 continue;
2141 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002142
2143 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2144 ALOGE("External displays are not supported by the vr hardware composer.");
2145 continue;
2146 }
2147
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002148 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002149 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002150 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002151 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002152 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002153
2154 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002155 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002156 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002157 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002158 DisplayDeviceState info;
2159 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002160 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2161 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002162 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002163 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002164 mInterceptor->saveDisplayCreation(info);
2165 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002166 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002167 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002168
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002169 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002170 if (idx >= 0) {
2171 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002172 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002173 mCurrentState.displays.removeItemsAt(idx);
2174 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002175 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002176 }
2177
2178 processDisplayChangesLocked();
2179 }
2180
2181 mPendingHotplugEvents.clear();
2182}
2183
Lloyd Pique99d3da52018-01-22 17:48:03 -08002184sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002185 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002186 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002187 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002188 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002189
Lloyd Pique99d3da52018-01-22 17:48:03 -08002190 if (hasWideColorDisplay) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002191 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002192 for (ColorMode colorMode : modes) {
2193 switch (colorMode) {
2194 case ColorMode::DISPLAY_P3:
2195 case ColorMode::ADOBE_RGB:
2196 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002197 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002198 break;
2199 default:
2200 break;
2201 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002202
Dominik Laskowski7e045462018-05-30 13:02:02 -07002203 std::vector<RenderIntent> renderIntents =
2204 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002205 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002206 }
2207 }
2208
Peiyong Lin62665892018-04-16 11:07:44 -07002209 HdrCapabilities hdrCapabilities;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002210 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002211
2212 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2213 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2214
2215 /*
2216 * Create our display's surface
2217 */
2218 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2219 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002220 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002221 renderSurface->setNativeWindow(nativeWindow.get());
2222 const int displayWidth = renderSurface->queryWidth();
2223 const int displayHeight = renderSurface->queryHeight();
2224
2225 // Make sure that composition can never be stalled by a virtual display
2226 // consumer that isn't processing buffers fast enough. We have to do this
2227 // in two places:
2228 // * Here, in case the display is composed entirely by HWC.
2229 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2230 // window's swap interval in eglMakeCurrent, so they'll override the
2231 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002232 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002233 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2234 }
2235
2236 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002237 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002238
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002239 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002240 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2241 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2242 displayHeight, hasWideColorGamut, hdrCapabilities,
2243 getHwComposer().getSupportedPerFrameMetadata(displayId),
2244 hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002245
2246 if (maxFrameBufferAcquiredBuffers >= 3) {
2247 nativeWindowSurface->preallocateBuffers();
2248 }
2249
2250 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002251 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2252 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002253 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002254 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002255 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002256 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002257 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002258 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002259 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002260 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002261 display->setLayerStack(state.layerStack);
2262 display->setProjection(state.orientation, state.viewport, state.frame);
2263 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002264
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002265 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002266}
2267
Lloyd Pique347200f2017-12-14 17:00:15 -08002268void SurfaceFlinger::processDisplayChangesLocked() {
2269 // here we take advantage of Vector's copy-on-write semantics to
2270 // improve performance by skipping the transaction entirely when
2271 // know that the lists are identical
2272 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2273 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2274 if (!curr.isIdenticalTo(draw)) {
2275 mVisibleRegionsDirty = true;
2276 const size_t cc = curr.size();
2277 size_t dc = draw.size();
2278
2279 // find the displays that were removed
2280 // (ie: in drawing state but not in current state)
2281 // also handle displays that changed
2282 // (ie: displays that are in both lists)
2283 for (size_t i = 0; i < dc;) {
2284 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2285 if (j < 0) {
2286 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002287 // Call makeCurrent() on the primary display so we can
2288 // be sure that nothing associated with this display
2289 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002290 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2291 defaultDisplay->makeCurrent();
2292 }
2293 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2294 display->disconnect(getHwComposer());
2295 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002296 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2297 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2298 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2299 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2300 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002301 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002302 } else {
2303 // this display is in both lists. see if something changed.
2304 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002305 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002306 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2307 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2308 if (state_binder != draw_binder) {
2309 // changing the surface is like destroying and
2310 // recreating the DisplayDevice, so we just remove it
2311 // from the drawing state, so that it get re-added
2312 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002313 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2314 display->disconnect(getHwComposer());
2315 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002316 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002317 mDrawingState.displays.removeItemsAt(i);
2318 dc--;
2319 // at this point we must loop to the next item
2320 continue;
2321 }
2322
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002323 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002324 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002325 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002326 }
2327 if ((state.orientation != draw[i].orientation) ||
2328 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002329 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002330 }
2331 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002332 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002333 }
2334 }
2335 }
2336 ++i;
2337 }
2338
2339 // find displays that were added
2340 // (ie: in current state but not in drawing state)
2341 for (size_t i = 0; i < cc; i++) {
2342 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2343 const DisplayDeviceState& state(curr[i]);
2344
2345 sp<DisplaySurface> dispSurface;
2346 sp<IGraphicBufferProducer> producer;
2347 sp<IGraphicBufferProducer> bqProducer;
2348 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002349 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002350
Dominik Laskowski7e045462018-05-30 13:02:02 -07002351 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002352 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002353 // Virtual displays without a surface are dormant:
2354 // they have external state (layer stack, projection,
2355 // etc.) but no internal state (i.e. a DisplayDevice).
2356 if (state.surface != nullptr) {
2357 // Allow VR composer to use virtual displays.
2358 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2359 int width = 0;
2360 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2361 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2362 int height = 0;
2363 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2364 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2365 int intFormat = 0;
2366 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2367 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002368 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002369
Dominik Laskowski7e045462018-05-30 13:02:02 -07002370 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2371 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002372 }
2373
2374 // TODO: Plumb requested format back up to consumer
2375
2376 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002377 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002378 bqProducer, bqConsumer,
2379 state.displayName);
2380
2381 dispSurface = vds;
2382 producer = vds;
2383 }
2384 } else {
2385 ALOGE_IF(state.surface != nullptr,
2386 "adding a supported display, but rendering "
2387 "surface is provided (%p), ignoring it",
2388 state.surface.get());
2389
Dominik Laskowski7e045462018-05-30 13:02:02 -07002390 displayId = state.type;
2391 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002392 producer = bqProducer;
2393 }
2394
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002395 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002396 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002397 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002398 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002399 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002400 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002401 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2402 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2403 true);
2404 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2405 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2406 true);
2407 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002408 }
2409 }
2410 }
2411 }
2412 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002413
2414 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002415}
2416
Mathias Agopian87baae12012-07-31 12:38:26 -07002417void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002418{
Dan Stoza7dde5992015-05-22 09:51:44 -07002419 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002420 mCurrentState.traverseInZOrder([](Layer* layer) {
2421 layer->notifyAvailableFrames();
2422 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002423
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002424 /*
2425 * Traversal of the children
2426 * (perform the transaction for each of them if needed)
2427 */
2428
Mathias Agopian3559b072012-08-15 13:46:03 -07002429 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002430 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002431 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002432 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002433
2434 const uint32_t flags = layer->doTransaction(0);
2435 if (flags & Layer::eVisibleRegion)
2436 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002437 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002438 }
2439
2440 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002441 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002442 */
2443
Mathias Agopiane57f2922012-08-09 16:29:12 -07002444 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002445 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002446 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002447 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002448
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002449 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002450 // The transform hint might have changed for some layers
2451 // (either because a display has changed, or because a layer
2452 // as changed).
2453 //
2454 // Walk through all the layers in currentLayers,
2455 // and update their transform hint.
2456 //
2457 // If a layer is visible only on a single display, then that
2458 // display is used to calculate the hint, otherwise we use the
2459 // default display.
2460 //
2461 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2462 // the hint is set before we acquire a buffer from the surface texture.
2463 //
2464 // NOTE: layer transactions have taken place already, so we use their
2465 // drawing state. However, SurfaceFlinger's own transaction has not
2466 // happened yet, so we must use the current state layer list
2467 // (soon to become the drawing state list).
2468 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002469 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002470 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002471 bool first = true;
2472 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002473 // NOTE: we rely on the fact that layers are sorted by
2474 // layerStack first (so we don't have to traverse the list
2475 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002476 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002477 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002478 currentlayerStack = layerStack;
2479 // figure out if this layerstack is mirrored
2480 // (more than one display) if so, pick the default display,
2481 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002482 hintDisplay = nullptr;
2483 for (const auto& [token, display] : mDisplays) {
2484 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2485 if (hintDisplay) {
2486 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002487 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002488 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002489 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002490 }
2491 }
2492 }
2493 }
Chet Haase91d25932013-04-11 15:24:55 -07002494
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002495 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002496 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2497 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002498
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002499 // could be null when this layer is using a layerStack
2500 // that is not visible on any display. Also can occur at
2501 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002502 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002503 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002504
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002505 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002506 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002507 if (hintDisplay) {
2508 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002509 }
Robert Carr2047fae2016-11-28 14:09:09 -08002510
2511 first = false;
2512 });
Mathias Agopian84300952012-11-21 16:02:13 -08002513 }
2514
2515
Mathias Agopian3559b072012-08-15 13:46:03 -07002516 /*
2517 * Perform our own transaction if needed
2518 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002519
2520 if (mLayersAdded) {
2521 mLayersAdded = false;
2522 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002523 mVisibleRegionsDirty = true;
2524 }
2525
2526 // some layers might have been removed, so
2527 // we need to update the regions they're exposing.
2528 if (mLayersRemoved) {
2529 mLayersRemoved = false;
2530 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002531 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002532 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002533 // this layer is not visible anymore
2534 // TODO: we could traverse the tree from front to back and
2535 // compute the actual visible region
2536 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002537 Region visibleReg;
2538 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002539 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002540 }
Robert Carr2047fae2016-11-28 14:09:09 -08002541 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002542 }
2543
2544 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002545
2546 updateCursorAsync();
2547}
2548
2549void SurfaceFlinger::updateCursorAsync()
2550{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002551 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002552 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002553 continue;
2554 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002555
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002556 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2557 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002558 }
2559 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002560}
2561
2562void SurfaceFlinger::commitTransaction()
2563{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002564 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002565 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002566 for (const auto& l : mLayersPendingRemoval) {
2567 recordBufferingStats(l->getName().string(),
2568 l->getOccupancyHistory(true));
2569 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002570 }
2571 mLayersPendingRemoval.clear();
2572 }
2573
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002574 // If this transaction is part of a window animation then the next frame
2575 // we composite should be considered an animation as well.
2576 mAnimCompositionPending = mAnimTransactionPending;
2577
Mathias Agopian4fec8732012-06-29 14:12:52 -07002578 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002579 // clear the "changed" flags in current state
2580 mCurrentState.colorMatrixChanged = false;
2581
Robert Carr1f0a16a2016-10-24 16:27:39 -07002582 mDrawingState.traverseInZOrder([](Layer* layer) {
2583 layer->commitChildList();
2584 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002585 mTransactionPending = false;
2586 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002587 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588}
2589
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002590void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2591 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002592 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002593 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002594
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595 Region aboveOpaqueLayers;
2596 Region aboveCoveredLayers;
2597 Region dirty;
2598
Mathias Agopian87baae12012-07-31 12:38:26 -07002599 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600
Robert Carr2047fae2016-11-28 14:09:09 -08002601 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002603 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604
Jesse Hall01e29052013-02-19 16:13:35 -08002605 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002606 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002607 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002608 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002609
Mathias Agopianab028732010-03-16 16:41:46 -07002610 /*
2611 * opaqueRegion: area of a surface that is fully opaque.
2612 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002614
2615 /*
2616 * visibleRegion: area of a surface that is visible on screen
2617 * and not fully transparent. This is essentially the layer's
2618 * footprint minus the opaque regions above it.
2619 * Areas covered by a translucent surface are considered visible.
2620 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002622
2623 /*
2624 * coveredRegion: area of a surface that is covered by all
2625 * visible regions above it (which includes the translucent areas).
2626 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002627 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002628
Jesse Halla8026d22012-09-25 13:25:04 -07002629 /*
2630 * transparentRegion: area of a surface that is hinted to be completely
2631 * transparent. This is only used to tell when the layer has no visible
2632 * non-transparent regions and can be removed from the layer list. It
2633 * does not affect the visibleRegion of this layer or any layers
2634 * beneath it. The hint may not be correct if apps don't respect the
2635 * SurfaceView restrictions (which, sadly, some don't).
2636 */
2637 Region transparentRegion;
2638
Mathias Agopianab028732010-03-16 16:41:46 -07002639
2640 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002641 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002642 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002643 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002644 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002645 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002646 if (!visibleRegion.isEmpty()) {
2647 // Remove the transparent area from the visible region
2648 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002649 if (tr.preserveRects()) {
2650 // transform the transparent region
2651 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002652 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002653 // transformation too complex, can't do the
2654 // transparent region optimization.
2655 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002656 }
Mathias Agopianab028732010-03-16 16:41:46 -07002657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658
Mathias Agopianab028732010-03-16 16:41:46 -07002659 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002660 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002661 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002662 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2663 // the opaque region is the layer's footprint
2664 opaqueRegion = visibleRegion;
2665 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666 }
2667 }
2668
Robert Carre5f4f692018-01-12 13:12:28 -08002669 if (visibleRegion.isEmpty()) {
2670 layer->clearVisibilityRegions();
2671 return;
2672 }
2673
Mathias Agopianab028732010-03-16 16:41:46 -07002674 // Clip the covered region to the visible region
2675 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2676
2677 // Update aboveCoveredLayers for next (lower) layer
2678 aboveCoveredLayers.orSelf(visibleRegion);
2679
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680 // subtract the opaque region covered by the layers above us
2681 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682
2683 // compute this layer's dirty region
2684 if (layer->contentDirty) {
2685 // we need to invalidate the whole region
2686 dirty = visibleRegion;
2687 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002688 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002689 layer->contentDirty = false;
2690 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002691 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002692 * the exposed region consists of two components:
2693 * 1) what's VISIBLE now and was COVERED before
2694 * 2) what's EXPOSED now less what was EXPOSED before
2695 *
2696 * note that (1) is conservative, we start with the whole
2697 * visible region but only keep what used to be covered by
2698 * something -- which mean it may have been exposed.
2699 *
2700 * (2) handles areas that were not covered by anything but got
2701 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002702 */
Mathias Agopianab028732010-03-16 16:41:46 -07002703 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002704 const Region oldVisibleRegion = layer->visibleRegion;
2705 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002706 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2707 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708 }
2709 dirty.subtractSelf(aboveOpaqueLayers);
2710
2711 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002712 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713
Mathias Agopianab028732010-03-16 16:41:46 -07002714 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002716
Jesse Halla8026d22012-09-25 13:25:04 -07002717 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718 layer->setVisibleRegion(visibleRegion);
2719 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002720 layer->setVisibleNonTransparentRegion(
2721 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002722 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723
Mathias Agopian87baae12012-07-31 12:38:26 -07002724 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725}
2726
Chia-I Wuab0c3192017-08-01 11:29:00 -07002727void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002728 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002729 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2730 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002731 }
2732 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002733}
2734
Dan Stoza6b9454d2014-11-07 16:00:59 -08002735bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002737 ALOGV("handlePageFlip");
2738
Brian Andersond6927fb2016-07-23 23:37:30 -07002739 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002740
Mathias Agopian4fec8732012-06-29 14:12:52 -07002741 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002742 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002743 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002744
2745 // Store the set of layers that need updates. This set must not change as
2746 // buffers are being latched, as this could result in a deadlock.
2747 // Example: Two producers share the same command stream and:
2748 // 1.) Layer 0 is latched
2749 // 2.) Layer 0 gets a new frame
2750 // 2.) Layer 1 gets a new frame
2751 // 3.) Layer 1 is latched.
2752 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2753 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002754 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002755 if (layer->hasQueuedFrame()) {
2756 frameQueued = true;
2757 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002758 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002759 } else {
2760 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002761 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002762 } else {
2763 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002764 }
Robert Carr2047fae2016-11-28 14:09:09 -08002765 });
2766
Dan Stoza9e56aa02015-11-02 13:00:03 -08002767 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002768 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002769 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002770 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002771 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002772 newDataLatched = true;
2773 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002774 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002775
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002776 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002777
2778 // If we will need to wake up at some time in the future to deal with a
2779 // queued frame that shouldn't be displayed during this vsync period, wake
2780 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002781 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002782 signalLayerUpdate();
2783 }
2784
2785 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002786 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787}
2788
Mathias Agopianad456f92011-01-13 17:53:01 -08002789void SurfaceFlinger::invalidateHwcGeometry()
2790{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002791 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002792}
2793
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002794void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2795 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002796 // We only need to actually compose the display if:
2797 // 1) It is being handled by hardware composer, which may need this to
2798 // keep its virtual display state machine in sync, or
2799 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002800 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002801 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002802 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002803 return;
2804 }
2805
Dan Stoza9e56aa02015-11-02 13:00:03 -08002806 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002807 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002808
2809 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002810 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811}
2812
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002813bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002814 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002815
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002816 const Region bounds(display->bounds());
2817 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002818 const auto displayId = display->getId();
2819 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002820 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002821
Chia-I Wu8e50e692018-05-04 10:12:37 -07002822 bool applyColorMatrix = false;
Peiyong Lin00f9c022018-05-09 15:35:33 -07002823 bool needsLegacyColorMatrix = false;
2824 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002825
Dan Stoza9e56aa02015-11-02 13:00:03 -08002826 if (hasClientComposition) {
2827 ALOGV("hasClientComposition");
2828
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002829 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002830 if (display->hasWideColorGamut()) {
2831 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002832 }
2833 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002834 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002835 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002836
Dominik Laskowski7e045462018-05-30 13:02:02 -07002837 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002838 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2839 HWC2::Capability::SkipClientColorTransform);
2840
2841 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2842 if (applyColorMatrix) {
Peiyong Lin00f9c022018-05-09 15:35:33 -07002843 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002844 }
2845
Chia-I Wubbb44462018-05-21 15:33:27 -07002846 needsLegacyColorMatrix =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002847 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2848 outputDataspace != Dataspace::UNKNOWN && outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002849
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002850 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002851 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002852 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002853 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002854
2855 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002856 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002857 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2858 }
2859 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002860 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002861
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002862 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002863 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002864 // when using overlays, we assume a fully transparent framebuffer
2865 // NOTE: we could reduce how much we need to clear, for instance
2866 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002867 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002868 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002869 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002870 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002871 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002872 // we're left with the letterbox region
2873 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002874 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002875
2876 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002877 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002878
Mathias Agopianb9494d52012-04-18 02:28:45 -07002879 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002880 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002881 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002882 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002883 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002884 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002885
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002886 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002887 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002888 // scissor on the main display. It should never be needed
2889 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002890 const Rect& bounds = display->getBounds();
2891 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002892 if (scissor != bounds) {
2893 // scissor doesn't match the screen's dimensions, so we
2894 // need to clear everything outside of it and enable
2895 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002896
Mathias Agopianf45c5102012-10-24 16:29:17 -07002897 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002898 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002899 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002900 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002901 }
2902 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002903 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002904
Mathias Agopian85d751c2012-08-29 16:59:24 -07002905 /*
2906 * and then, render the layers targeted at the framebuffer
2907 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002908
Dan Stoza9e56aa02015-11-02 13:00:03 -08002909 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002910 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002911 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002912 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002913 const Region clip(bounds.intersect(
2914 displayTransform.transform(layer->visibleRegion)));
2915 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002916 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002917 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002918 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002919 case HWC2::Composition::Cursor:
2920 case HWC2::Composition::Device:
2921 case HWC2::Composition::Sideband:
2922 case HWC2::Composition::SolidColor: {
2923 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002924 if (layer->getClearClientTarget(displayId) && !firstLayer &&
2925 layer->isOpaque(state) && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002926 // never clear the very first layer since we're
2927 // guaranteed the FB is already cleared
2928 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002929 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002930 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002931 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002932 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002933 // switch color matrices lazily
Peiyong Lin00f9c022018-05-09 15:35:33 -07002934 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
2935 if (!legacyColorMatrixApplied) {
2936 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
2937 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002938 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07002939 } else if (legacyColorMatrixApplied) {
2940 getRenderEngine().setSaturationMatrix(mat4());
2941 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002942 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07002943
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002944 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002945 break;
2946 }
2947 default:
2948 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002949 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002950 } else {
2951 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002952 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002953 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002954 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002955
Peiyong Lin00f9c022018-05-09 15:35:33 -07002956 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002957 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002958 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07002959 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
2960 getRenderEngine().setSaturationMatrix(mat4());
2961 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002962
Mathias Agopianf45c5102012-10-24 16:29:17 -07002963 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002964 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002965 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002966}
2967
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002968void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2969 const Region& region) const {
2970 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002971 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002972 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002973}
2974
Dan Stoza7d89d062015-04-30 13:29:25 -07002975status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002976 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002977 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002978 const sp<Layer>& lbc,
2979 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002980{
Dan Stoza7d89d062015-04-30 13:29:25 -07002981 // add this layer to the current state list
2982 {
2983 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002984 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002985 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2986 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002987 return NO_MEMORY;
2988 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002989 if (parent == nullptr) {
2990 mCurrentState.layersSortedByZ.add(lbc);
2991 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002992 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002993 ALOGE("addClientLayer called with a removed parent");
2994 return NAME_NOT_FOUND;
2995 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002996 parent->addChild(lbc);
2997 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002998
Yiwei Zhang243b3782018-05-15 17:40:04 -07002999 if (gbc != nullptr) {
3000 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3001 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3002 mMaxGraphicBufferProducerListSize,
3003 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3004 mGraphicBufferProducerList.size(),
3005 mMaxGraphicBufferProducerListSize, mNumLayers);
3006 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003007 mLayersAdded = true;
3008 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003009 }
3010
Mathias Agopian96f08192010-06-02 23:28:45 -07003011 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003012 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003013
Dan Stoza7d89d062015-04-30 13:29:25 -07003014 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003015}
3016
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003017status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003018 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003019 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3020}
Robert Carr7f9b8992017-03-10 11:08:39 -08003021
chaviwca27f252018-02-06 16:46:39 -08003022status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3023 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003024 if (layer->isPendingRemoval()) {
3025 return NO_ERROR;
3026 }
3027
Robert Carr1f0a16a2016-10-24 16:27:39 -07003028 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003029 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003030 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003031 if (topLevelOnly) {
3032 return NO_ERROR;
3033 }
3034
Chia-I Wu98f1c102017-05-30 14:54:08 -07003035 sp<Layer> ancestor = p;
3036 while (ancestor->getParent() != nullptr) {
3037 ancestor = ancestor->getParent();
3038 }
3039 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3040 ALOGE("removeLayer called with a layer whose parent has been removed");
3041 return NAME_NOT_FOUND;
3042 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003043
3044 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003045 } else {
3046 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003047 }
3048
Robert Carr136e2f62017-02-08 17:54:29 -08003049 // As a matter of normal operation, the LayerCleaner will produce a second
3050 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3051 // so we will succeed in promoting it, but it's already been removed
3052 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3053 // otherwise something has gone wrong and we are leaking the layer.
3054 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003055 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3056 layer->getName().string(),
3057 (p != nullptr) ? p->getName().string() : "no-parent");
3058 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003059 } else if (index < 0) {
3060 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003061 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003062
Chia-I Wuc6657022017-08-15 11:18:17 -07003063 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003064 mLayersPendingRemoval.add(layer);
3065 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003066 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003067 setTransactionFlags(eTransactionNeeded);
3068 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003069}
3070
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003071uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003072 return android_atomic_release_load(&mTransactionFlags);
3073}
3074
Mathias Agopian3f844832013-08-07 21:24:32 -07003075uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3077}
3078
Mathias Agopian3f844832013-08-07 21:24:32 -07003079uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003080 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3081}
3082
3083uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3084 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003085 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003086 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003088 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003089 }
3090 return old;
3091}
3092
chaviwca27f252018-02-06 16:46:39 -08003093bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3094 for (const ComposerState& state : states) {
3095 // Here we need to check that the interface we're given is indeed
3096 // one of our own. A malicious client could give us a nullptr
3097 // IInterface, or one of its own or even one of our own but a
3098 // different type. All these situations would cause us to crash.
3099 if (state.client == nullptr) {
3100 return true;
3101 }
3102
3103 sp<IBinder> binder = IInterface::asBinder(state.client);
3104 if (binder == nullptr) {
3105 return true;
3106 }
3107
3108 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3109 return true;
3110 }
3111 }
3112 return false;
3113}
3114
Mathias Agopian8b33f032012-07-24 20:43:54 -07003115void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003116 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003117 const Vector<DisplayState>& displays,
3118 uint32_t flags)
3119{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003120 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003121 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003122 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003123
chaviwca27f252018-02-06 16:46:39 -08003124 if (containsAnyInvalidClientState(states)) {
3125 return;
3126 }
3127
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003128 if (flags & eAnimation) {
3129 // For window updates that are part of an animation we must wait for
3130 // previous animation "frames" to be handled.
3131 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003132 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003133 if (CC_UNLIKELY(err != NO_ERROR)) {
3134 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003135 // caller after a few seconds.
3136 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3137 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003138 mAnimTransactionPending = false;
3139 break;
3140 }
3141 }
3142 }
3143
chaviwca27f252018-02-06 16:46:39 -08003144 for (const DisplayState& display : displays) {
3145 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003146 }
3147
chaviwca27f252018-02-06 16:46:39 -08003148 for (const ComposerState& state : states) {
3149 transactionFlags |= setClientStateLocked(state);
3150 }
3151
3152 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3153 // as destroyed should only occur after setting all other states. This is to allow for a
3154 // child re-parent to happen before marking its original parent as destroyed (which would
3155 // then mark the child as destroyed).
3156 for (const ComposerState& state : states) {
3157 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003158 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003159
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003160 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3161 // anyway. This can be used as a flush mechanism for previous async transactions.
3162 // Empty animation transaction can be used to simulate back-pressure, so also force a
3163 // transaction for empty animation transactions.
3164 if (transactionFlags == 0 &&
3165 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003166 transactionFlags = eTransactionNeeded;
3167 }
3168
Mathias Agopian386aa982011-11-07 21:58:03 -08003169 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003170 if (mInterceptor->isEnabled()) {
3171 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003172 }
Irvel468051e2016-06-13 16:44:44 -07003173
Mathias Agopian386aa982011-11-07 21:58:03 -08003174 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003175 const auto start = (flags & eEarlyWakeup)
3176 ? VSyncModulator::TransactionStart::EARLY
3177 : VSyncModulator::TransactionStart::NORMAL;
3178 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003179
3180 // if this is a synchronous transaction, wait for it to take effect
3181 // before returning.
3182 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003183 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003184 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003185 if (flags & eAnimation) {
3186 mAnimTransactionPending = true;
3187 }
3188 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003189 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3190 if (CC_UNLIKELY(err != NO_ERROR)) {
3191 // just in case something goes wrong in SF, return to the
3192 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003193 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3194 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003195 break;
3196 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003197 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003198 }
3199}
3200
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003201uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3202 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3203 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003204
Mathias Agopiane57f2922012-08-09 16:29:12 -07003205 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003206 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3207
3208 const uint32_t what = s.what;
3209 if (what & DisplayState::eSurfaceChanged) {
3210 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3211 state.surface = s.surface;
3212 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003213 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003214 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003215 if (what & DisplayState::eLayerStackChanged) {
3216 if (state.layerStack != s.layerStack) {
3217 state.layerStack = s.layerStack;
3218 flags |= eDisplayTransactionNeeded;
3219 }
3220 }
3221 if (what & DisplayState::eDisplayProjectionChanged) {
3222 if (state.orientation != s.orientation) {
3223 state.orientation = s.orientation;
3224 flags |= eDisplayTransactionNeeded;
3225 }
3226 if (state.frame != s.frame) {
3227 state.frame = s.frame;
3228 flags |= eDisplayTransactionNeeded;
3229 }
3230 if (state.viewport != s.viewport) {
3231 state.viewport = s.viewport;
3232 flags |= eDisplayTransactionNeeded;
3233 }
3234 }
3235 if (what & DisplayState::eDisplaySizeChanged) {
3236 if (state.width != s.width) {
3237 state.width = s.width;
3238 flags |= eDisplayTransactionNeeded;
3239 }
3240 if (state.height != s.height) {
3241 state.height = s.height;
3242 flags |= eDisplayTransactionNeeded;
3243 }
3244 }
3245
Mathias Agopiane57f2922012-08-09 16:29:12 -07003246 return flags;
3247}
3248
chaviwca27f252018-02-06 16:46:39 -08003249uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3250 const layer_state_t& s = composerState.state;
3251 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3252
Mathias Agopian13127d82013-03-05 17:47:11 -08003253 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003254 if (layer == nullptr) {
3255 return 0;
3256 }
3257
3258 if (layer->isPendingRemoval()) {
3259 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3260 return 0;
3261 }
3262
3263 uint32_t flags = 0;
3264
3265 const uint32_t what = s.what;
3266 bool geometryAppliesWithResize =
3267 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003268
3269 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3270 // pending state will also be deferred.
3271 if (what & layer_state_t::eDeferTransaction) {
3272 layer->pushPendingState();
3273 }
3274
chaviw8b3871a2017-11-01 17:41:01 -07003275 if (what & layer_state_t::ePositionChanged) {
3276 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3277 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003278 }
chaviw8b3871a2017-11-01 17:41:01 -07003279 }
3280 if (what & layer_state_t::eLayerChanged) {
3281 // NOTE: index needs to be calculated before we update the state
3282 const auto& p = layer->getParent();
3283 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003284 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003285 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003286 mCurrentState.layersSortedByZ.removeAt(idx);
3287 mCurrentState.layersSortedByZ.add(layer);
3288 // we need traversal (state changed)
3289 // AND transaction (list changed)
3290 flags |= eTransactionNeeded|eTraversalNeeded;
3291 }
chaviw8b3871a2017-11-01 17:41:01 -07003292 } else {
3293 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003294 flags |= eTransactionNeeded|eTraversalNeeded;
3295 }
3296 }
chaviw8b3871a2017-11-01 17:41:01 -07003297 }
3298 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003299 // NOTE: index needs to be calculated before we update the state
3300 const auto& p = layer->getParent();
3301 if (p == nullptr) {
3302 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3303 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3304 mCurrentState.layersSortedByZ.removeAt(idx);
3305 mCurrentState.layersSortedByZ.add(layer);
3306 // we need traversal (state changed)
3307 // AND transaction (list changed)
3308 flags |= eTransactionNeeded|eTraversalNeeded;
3309 }
3310 } else {
3311 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3312 flags |= eTransactionNeeded|eTraversalNeeded;
3313 }
chaviw8b3871a2017-11-01 17:41:01 -07003314 }
3315 }
3316 if (what & layer_state_t::eSizeChanged) {
3317 if (layer->setSize(s.w, s.h)) {
3318 flags |= eTraversalNeeded;
3319 }
3320 }
3321 if (what & layer_state_t::eAlphaChanged) {
3322 if (layer->setAlpha(s.alpha))
3323 flags |= eTraversalNeeded;
3324 }
3325 if (what & layer_state_t::eColorChanged) {
3326 if (layer->setColor(s.color))
3327 flags |= eTraversalNeeded;
3328 }
3329 if (what & layer_state_t::eMatrixChanged) {
3330 if (layer->setMatrix(s.matrix))
3331 flags |= eTraversalNeeded;
3332 }
3333 if (what & layer_state_t::eTransparentRegionChanged) {
3334 if (layer->setTransparentRegionHint(s.transparentRegion))
3335 flags |= eTraversalNeeded;
3336 }
3337 if (what & layer_state_t::eFlagsChanged) {
3338 if (layer->setFlags(s.flags, s.mask))
3339 flags |= eTraversalNeeded;
3340 }
3341 if (what & layer_state_t::eCropChanged) {
3342 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3343 flags |= eTraversalNeeded;
3344 }
3345 if (what & layer_state_t::eFinalCropChanged) {
3346 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3347 flags |= eTraversalNeeded;
3348 }
3349 if (what & layer_state_t::eLayerStackChanged) {
3350 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3351 // We only allow setting layer stacks for top level layers,
3352 // everything else inherits layer stack from its parent.
3353 if (layer->hasParent()) {
3354 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3355 layer->getName().string());
3356 } else if (idx < 0) {
3357 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3358 "that also does not appear in the top level layer list. Something"
3359 " has gone wrong.", layer->getName().string());
3360 } else if (layer->setLayerStack(s.layerStack)) {
3361 mCurrentState.layersSortedByZ.removeAt(idx);
3362 mCurrentState.layersSortedByZ.add(layer);
3363 // we need traversal (state changed)
3364 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003365 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003366 }
3367 }
3368 if (what & layer_state_t::eDeferTransaction) {
3369 if (s.barrierHandle != nullptr) {
3370 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3371 } else if (s.barrierGbp != nullptr) {
3372 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3373 if (authenticateSurfaceTextureLocked(gbp)) {
3374 const auto& otherLayer =
3375 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3376 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3377 } else {
3378 ALOGE("Attempt to defer transaction to to an"
3379 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003380 }
3381 }
chaviw8b3871a2017-11-01 17:41:01 -07003382 // We don't trigger a traversal here because if no other state is
3383 // changed, we don't want this to cause any more work
3384 }
3385 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003386 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003387 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003388 if (!hadParent) {
3389 mCurrentState.layersSortedByZ.remove(layer);
3390 }
chaviw8b3871a2017-11-01 17:41:01 -07003391 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003392 }
chaviw8b3871a2017-11-01 17:41:01 -07003393 }
3394 if (what & layer_state_t::eReparentChildren) {
3395 if (layer->reparentChildren(s.reparentHandle)) {
3396 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003397 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003398 }
chaviw8b3871a2017-11-01 17:41:01 -07003399 if (what & layer_state_t::eDetachChildren) {
3400 layer->detachChildren();
3401 }
3402 if (what & layer_state_t::eOverrideScalingModeChanged) {
3403 layer->setOverrideScalingMode(s.overrideScalingMode);
3404 // We don't trigger a traversal here because if no other state is
3405 // changed, we don't want this to cause any more work
3406 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003407 return flags;
3408}
3409
chaviwca27f252018-02-06 16:46:39 -08003410void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3411 const layer_state_t& state = composerState.state;
3412 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3413
3414 sp<Layer> layer(client->getLayerUser(state.surface));
3415 if (layer == nullptr) {
3416 return;
3417 }
3418
3419 if (layer->isPendingRemoval()) {
3420 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3421 return;
3422 }
3423
3424 if (state.what & layer_state_t::eDestroySurface) {
3425 removeLayerLocked(mStateLock, layer);
3426 }
3427}
3428
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003429status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003430 const String8& name,
3431 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003432 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003433 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003434 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003435{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003436 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003437 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003438 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003439 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003440 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003441
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003442 status_t result = NO_ERROR;
3443
3444 sp<Layer> layer;
3445
Cody Northropbc755282017-03-31 12:00:08 -06003446 String8 uniqueName = getUniqueLayerName(name);
3447
Mathias Agopian3165cc22012-08-08 19:42:09 -07003448 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3449 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003450 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003451 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003452 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003453
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003454 break;
chaviw13fdc492017-06-27 12:40:18 -07003455 case ISurfaceComposerClient::eFXSurfaceColor:
3456 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003457 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003458 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003459 break;
3460 default:
3461 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003462 break;
3463 }
3464
Dan Stoza7d89d062015-04-30 13:29:25 -07003465 if (result != NO_ERROR) {
3466 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003467 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003468
Chia-I Wuab0c3192017-08-01 11:29:00 -07003469 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3470 // TODO b/64227542
3471 if (windowType == 441731) {
3472 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3473 layer->setPrimaryDisplayOnly();
3474 }
3475
Albert Chaulk479c60c2017-01-27 14:21:34 -05003476 layer->setInfo(windowType, ownerUid);
3477
Robert Carr1f0a16a2016-10-24 16:27:39 -07003478 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003479 if (result != NO_ERROR) {
3480 return result;
3481 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003482 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003483
3484 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003485 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003486}
3487
Cody Northropbc755282017-03-31 12:00:08 -06003488String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3489{
3490 bool matchFound = true;
3491 uint32_t dupeCounter = 0;
3492
3493 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3494 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3495
3496 // Loop over layers until we're sure there is no matching name
3497 while (matchFound) {
3498 matchFound = false;
3499 mDrawingState.traverseInZOrder([&](Layer* layer) {
3500 if (layer->getName() == uniqueName) {
3501 matchFound = true;
3502 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3503 }
3504 });
3505 }
3506
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003507 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3508 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003509
3510 return uniqueName;
3511}
3512
David Sodman0c69cad2017-08-21 12:12:51 -07003513status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003514 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3515 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003516{
3517 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003518 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003519 case PIXEL_FORMAT_TRANSPARENT:
3520 case PIXEL_FORMAT_TRANSLUCENT:
3521 format = PIXEL_FORMAT_RGBA_8888;
3522 break;
3523 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003524 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003525 break;
3526 }
3527
David Sodman0c69cad2017-08-21 12:12:51 -07003528 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3529 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003530 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003531 *handle = layer->getHandle();
3532 *gbp = layer->getProducer();
3533 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003534 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003535
David Sodman0c69cad2017-08-21 12:12:51 -07003536 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003537 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003538}
3539
chaviw13fdc492017-06-27 12:40:18 -07003540status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003541 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003542 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003543{
chaviw13fdc492017-06-27 12:40:18 -07003544 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003545 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003546 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003547}
3548
Mathias Agopianac9fa422013-02-11 16:40:36 -08003549status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003550{
Robert Carr9524cb32017-02-13 11:32:32 -08003551 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003552 status_t err = NO_ERROR;
3553 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003554 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003555 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003556 err = removeLayer(l);
3557 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3558 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003559 }
3560 return err;
3561}
3562
Mathias Agopian13127d82013-03-05 17:47:11 -08003563status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003564{
Mathias Agopian67106042013-03-14 19:18:13 -07003565 // called by ~LayerCleaner() when all references to the IBinder (handle)
3566 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003567 sp<Layer> l = layer.promote();
3568 if (l == nullptr) {
3569 // The layer has already been removed, carry on
3570 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003571 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003572 // If we have a parent, then we can continue to live as long as it does.
3573 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003574}
3575
Mathias Agopianb60314a2012-04-10 22:09:54 -07003576// ---------------------------------------------------------------------------
3577
Andy McFadden13a082e2012-08-24 10:16:42 -07003578void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003579 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003580 Vector<ComposerState> state;
3581 Vector<DisplayState> displays;
3582 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003583 d.what = DisplayState::eDisplayProjectionChanged |
3584 DisplayState::eLayerStackChanged;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003585 d.token = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003586 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003587 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003588 d.frame.makeInvalid();
3589 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003590 d.width = 0;
3591 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003592 displays.add(d);
3593 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003594 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3595 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003596
David Sodman105b7dc2017-11-04 20:28:14 -07003597 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003598 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003599 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003600
Brian Andersond0010582017-03-07 13:20:31 -08003601 // Use phase of 0 since phase is not known.
3602 // Use latency of 0, which will snap to the ideal latency.
3603 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003604}
3605
3606void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003607 // Async since we may be called from the main thread.
3608 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003609}
3610
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003611void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3612 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003613 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003614 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003615
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003616 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003617 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003618 return;
3619 }
3620
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003621 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003622 ALOGW("Trying to set power mode for virtual display");
3623 return;
3624 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003625
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003626 display->setPowerMode(mode);
3627
Lloyd Pique4dccc412018-01-22 17:21:36 -08003628 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003629 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003630 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003631 if (idx < 0) {
3632 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3633 return;
3634 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003635 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003636 }
3637
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003638 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003639 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003640 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003641 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003642 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003643 // FIXME: eventthread only knows about the main display right now
3644 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003645 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003646 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003647
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003648 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003649 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003650 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003651
3652 struct sched_param param = {0};
3653 param.sched_priority = 1;
3654 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3655 ALOGW("Couldn't set SCHED_FIFO on display on");
3656 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003657 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003658 // Turn off the display
3659 struct sched_param param = {0};
3660 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3661 ALOGW("Couldn't set SCHED_OTHER on display off");
3662 }
3663
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003664 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003665 disableHardwareVsync(true); // also cancels any in-progress resync
3666
Mathias Agopiancde87a32012-09-13 14:09:01 -07003667 // FIXME: eventthread only knows about the main display right now
3668 mEventThread->onScreenReleased();
3669 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003670
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003671 getHwComposer().setPowerMode(type, mode);
3672 mVisibleRegionsDirty = true;
3673 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003674 } else if (mode == HWC_POWER_MODE_DOZE ||
3675 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003676 // Update display while dozing
3677 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003678 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003679 // FIXME: eventthread only knows about the main display right now
3680 mEventThread->onScreenAcquired();
3681 resyncToHardwareVsync(true);
3682 }
3683 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3684 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003685 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003686 disableHardwareVsync(true); // also cancels any in-progress resync
3687 // FIXME: eventthread only knows about the main display right now
3688 mEventThread->onScreenReleased();
3689 }
3690 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003691 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003692 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003693 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003694 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003695
3696 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003697}
3698
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003699void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003700 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003701 const auto display = getDisplayDevice(displayToken);
3702 if (!display) {
3703 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3704 displayToken.get());
3705 } else if (display->isVirtual()) {
3706 ALOGW("Attempt to set power mode %d for virtual display", mode);
3707 } else {
3708 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003709 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003710 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003711}
3712
3713// ---------------------------------------------------------------------------
3714
Lloyd Pique755e3192018-01-31 16:46:15 -08003715status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3716 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003717 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003718
Mathias Agopianbd115332013-04-18 16:41:04 -07003719 IPCThreadState* ipc = IPCThreadState::self();
3720 const int pid = ipc->getCallingPid();
3721 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003722
Mathias Agopianbd115332013-04-18 16:41:04 -07003723 if ((uid != AID_SHELL) &&
3724 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003725 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003726 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003727 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003728 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003729 // (this would indicate SF is stuck, but we want to be able to
3730 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003731 status_t err = mStateLock.timedLock(s2ns(1));
3732 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003733 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003734 result.appendFormat(
3735 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3736 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003737 }
3738
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003739 bool dumpAll = true;
3740 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003741 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003742
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003743 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003744 if ((index < numArgs) &&
3745 (args[index] == String16("--list"))) {
3746 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003747 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003748 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003749 }
3750
3751 if ((index < numArgs) &&
3752 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003753 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003754 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003755 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003756 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003757
3758 if ((index < numArgs) &&
3759 (args[index] == String16("--latency-clear"))) {
3760 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003761 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003762 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003763 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003764
3765 if ((index < numArgs) &&
3766 (args[index] == String16("--dispsync"))) {
3767 index++;
3768 mPrimaryDispSync.dump(result);
3769 dumpAll = false;
3770 }
Dan Stozab90cf072015-03-05 11:05:59 -08003771
3772 if ((index < numArgs) &&
3773 (args[index] == String16("--static-screen"))) {
3774 index++;
3775 dumpStaticScreenStats(result);
3776 dumpAll = false;
3777 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003778
3779 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003780 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003781 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003782 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003783 dumpAll = false;
3784 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003785
3786 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3787 index++;
3788 dumpWideColorInfo(result);
3789 dumpAll = false;
3790 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003791
3792 if ((index < numArgs) &&
3793 (args[index] == String16("--enable-layer-stats"))) {
3794 index++;
3795 mLayerStats.enable();
3796 dumpAll = false;
3797 }
3798
3799 if ((index < numArgs) &&
3800 (args[index] == String16("--disable-layer-stats"))) {
3801 index++;
3802 mLayerStats.disable();
3803 dumpAll = false;
3804 }
3805
3806 if ((index < numArgs) &&
3807 (args[index] == String16("--clear-layer-stats"))) {
3808 index++;
3809 mLayerStats.clear();
3810 dumpAll = false;
3811 }
3812
3813 if ((index < numArgs) &&
3814 (args[index] == String16("--dump-layer-stats"))) {
3815 index++;
3816 mLayerStats.dump(result);
3817 dumpAll = false;
3818 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003819
3820 if ((index < numArgs) &&
3821 (args[index] == String16("--display-identification"))) {
3822 index++;
3823 dumpDisplayIdentificationData(result);
3824 dumpAll = false;
3825 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003826
3827 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3828 index++;
3829 mTimeStats.parseArgs(asProto, args, index, result);
3830 dumpAll = false;
3831 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003832 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003833
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003834 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003835 if (asProto) {
3836 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3837 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3838 } else {
3839 dumpAllLocked(args, index, result);
3840 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003841 }
3842
Mathias Agopian9795c422009-08-26 16:36:26 -07003843 if (locked) {
3844 mStateLock.unlock();
3845 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003846 }
3847 write(fd, result.string(), result.size());
3848 return NO_ERROR;
3849}
3850
Dan Stozac7014012014-02-14 15:03:43 -08003851void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3852 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003853{
Robert Carr2047fae2016-11-28 14:09:09 -08003854 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003855 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003856 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003857}
3858
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003859void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003860 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003861{
3862 String8 name;
3863 if (index < args.size()) {
3864 name = String8(args[index]);
3865 index++;
3866 }
3867
David Sodman105b7dc2017-11-04 20:28:14 -07003868 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003869 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003870 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003871
3872 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003873 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003874 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003875 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003876 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003877 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003878 }
Robert Carr2047fae2016-11-28 14:09:09 -08003879 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003880 }
3881}
3882
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003883void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003884 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003885{
3886 String8 name;
3887 if (index < args.size()) {
3888 name = String8(args[index]);
3889 index++;
3890 }
3891
Robert Carr2047fae2016-11-28 14:09:09 -08003892 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003893 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003894 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003895 }
Robert Carr2047fae2016-11-28 14:09:09 -08003896 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003897
Svetoslavd85084b2014-03-20 10:28:31 -07003898 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003899}
3900
Jamie Gennis6547ff42013-07-16 20:12:42 -07003901// This should only be called from the main thread. Otherwise it would need
3902// the lock and should use mCurrentState rather than mDrawingState.
3903void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003904 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003905 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003906 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003907
3908 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3909}
3910
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003911void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003912{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003913 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003914
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003915 if (isLayerTripleBufferingDisabled())
3916 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003917
3918 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003919 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003920 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003921 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003922 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3923 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003924 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003925}
3926
Dan Stozab90cf072015-03-05 11:05:59 -08003927void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3928{
3929 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003930 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3931 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003932 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003933 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003934 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3935 b + 1, bucketTimeSec, percent);
3936 }
David Sodman4a36e932017-11-07 14:29:47 -08003937 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003938 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003939 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003940 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003941 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003942}
3943
Dan Stozae77c7662016-05-13 11:37:28 -07003944void SurfaceFlinger::recordBufferingStats(const char* layerName,
3945 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003946 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3947 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003948 for (const auto& segment : history) {
3949 if (!segment.usedThirdBuffer) {
3950 stats.twoBufferTime += segment.totalTime;
3951 }
3952 if (segment.occupancyAverage < 1.0f) {
3953 stats.doubleBufferedTime += segment.totalTime;
3954 } else if (segment.occupancyAverage < 2.0f) {
3955 stats.tripleBufferedTime += segment.totalTime;
3956 }
3957 ++stats.numSegments;
3958 stats.totalTime += segment.totalTime;
3959 }
3960}
3961
Brian Andersond6927fb2016-07-23 23:37:30 -07003962void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3963 result.appendFormat("Layer frame timestamps:\n");
3964
3965 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3966 const size_t count = currentLayers.size();
3967 for (size_t i=0 ; i<count ; i++) {
3968 currentLayers[i]->dumpFrameEvents(result);
3969 }
3970}
3971
Dan Stozae77c7662016-05-13 11:37:28 -07003972void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3973 result.append("Buffering stats:\n");
3974 result.append(" [Layer name] <Active time> <Two buffer> "
3975 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003976 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003977 typedef std::tuple<std::string, float, float, float> BufferTuple;
3978 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003979 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003980 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003981 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003982 if (stats.numSegments == 0) {
3983 continue;
3984 }
3985 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3986 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3987 stats.totalTime;
3988 float doubleBufferRatio = static_cast<float>(
3989 stats.doubleBufferedTime) / stats.totalTime;
3990 float tripleBufferRatio = static_cast<float>(
3991 stats.tripleBufferedTime) / stats.totalTime;
3992 sorted.insert({activeTime, {name, twoBufferRatio,
3993 doubleBufferRatio, tripleBufferRatio}});
3994 }
3995 for (const auto& sortedPair : sorted) {
3996 float activeTime = sortedPair.first;
3997 const BufferTuple& values = sortedPair.second;
3998 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3999 std::get<0>(values).c_str(), activeTime,
4000 std::get<1>(values), std::get<2>(values),
4001 std::get<3>(values));
4002 }
4003 result.append("\n");
4004}
4005
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004006void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004007 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004008 const int32_t displayId = display->getId();
4009 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4010 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004011 continue;
4012 }
4013
Dominik Laskowski7e045462018-05-30 13:02:02 -07004014 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004015 uint8_t port;
4016 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004017 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004018 result.append("no identification data\n");
4019 continue;
4020 }
4021
4022 if (!isEdid(data)) {
4023 result.append("unknown identification data: ");
4024 for (uint8_t byte : data) {
4025 result.appendFormat("%x ", byte);
4026 }
4027 result.append("\n");
4028 continue;
4029 }
4030
4031 const auto edid = parseEdid(data);
4032 if (!edid) {
4033 result.append("invalid EDID: ");
4034 for (uint8_t byte : data) {
4035 result.appendFormat("%x ", byte);
4036 }
4037 result.append("\n");
4038 continue;
4039 }
4040
4041 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4042 result.append(edid->displayName.data(), edid->displayName.length());
4043 result.append("\"\n");
4044 }
4045 result.append("\n");
4046}
4047
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004048void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4049 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004050 result.appendFormat("DisplayColorSetting: %s\n",
4051 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004052
4053 // TODO: print out if wide-color mode is active or not
4054
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004055 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004056 const int32_t displayId = display->getId();
4057 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004058 continue;
4059 }
4060
Dominik Laskowski7e045462018-05-30 13:02:02 -07004061 result.appendFormat("Display %d color modes:\n", displayId);
4062 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004063 for (auto&& mode : modes) {
4064 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4065 }
4066
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004067 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004068 result.appendFormat(" Current color mode: %s (%d)\n",
4069 decodeColorMode(currentMode).c_str(), currentMode);
4070 }
4071 result.append("\n");
4072}
4073
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004074LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004075 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004076 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4077 const State& state = useDrawing ? mDrawingState : mCurrentState;
4078 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004079 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004080 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004081 });
4082
4083 return layersProto;
4084}
4085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004086LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004087 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004088
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004089 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004090 resolution->set_w(display.getWidth());
4091 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004093 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4094 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4095 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004096
Dominik Laskowski7e045462018-05-30 13:02:02 -07004097 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004098 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004099 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004100 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004101 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004102 }
4103 });
4104
4105 return layersProto;
4106}
4107
Mathias Agopian74d211a2013-04-22 16:55:35 +02004108void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4109 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004110{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004111 bool colorize = false;
4112 if (index < args.size()
4113 && (args[index] == String16("--color"))) {
4114 colorize = true;
4115 index++;
4116 }
4117
4118 Colorizer colorizer(colorize);
4119
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004120 // figure out if we're stuck somewhere
4121 const nsecs_t now = systemTime();
4122 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4123 const nsecs_t inTransaction(mDebugInTransaction);
4124 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4125 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4126
4127 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004128 * Dump library configuration.
4129 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004130
4131 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004132 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004133 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004134 appendSfConfigString(result);
4135 appendUiConfigString(result);
4136 appendGuiConfigString(result);
4137 result.append("\n");
4138
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004139 result.append("\nDisplay identification data:\n");
4140 dumpDisplayIdentificationData(result);
4141
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004142 result.append("\nWide-Color information:\n");
4143 dumpWideColorInfo(result);
4144
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004145 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004146 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004147 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004148 result.append(SyncFeatures::getInstance().toString());
4149 result.append("\n");
4150
David Sodman105b7dc2017-11-04 20:28:14 -07004151 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004152
Andy McFadden41d67d72014-04-25 16:58:34 -07004153 colorizer.bold(result);
4154 result.append("DispSync configuration: ");
4155 colorizer.reset(result);
Dan Stoza84d619e2018-03-28 17:07:36 -07004156 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4157 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4158 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004159 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004160 result.append("\n");
4161
Dan Stozab90cf072015-03-05 11:05:59 -08004162 // Dump static screen stats
4163 result.append("\n");
4164 dumpStaticScreenStats(result);
4165 result.append("\n");
4166
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004167 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4168
Dan Stozae77c7662016-05-13 11:37:28 -07004169 dumpBufferingStats(result);
4170
Andy McFadden4803b742012-09-24 19:07:20 -07004171 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004172 * Dump the visible layer list
4173 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004174 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004175 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004176 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4177 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004178 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004179
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004180 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004181 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004182 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004183 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004184
4185 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004186 * Dump Display state
4187 */
4188
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004189 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004190 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004191 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004192 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004193 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004194 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004195 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004196
4197 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004198 * Dump SurfaceFlinger global state
4199 */
4200
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004201 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004202 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004203 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004204
Mathias Agopian888c8222012-08-04 21:10:38 -07004205 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004206 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004207
David Sodmanbc815282017-11-05 18:57:52 -08004208 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004209
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004210 if (display) {
4211 display->undefinedRegion.dump(result, "undefinedRegion");
4212 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4213 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004214 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004215 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004216 " last eglSwapBuffers() time: %f us\n"
4217 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004218 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004219 " refresh-rate : %f fps\n"
4220 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004221 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004222 " gpu_to_cpu_unsupported : %d\n"
4223 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004224 mLastSwapBufferTime/1000.0,
4225 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004226 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004227 1e9 / activeConfig->getVsyncPeriod(),
4228 activeConfig->getDpiX(),
4229 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004230 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004231
Mathias Agopian74d211a2013-04-22 16:55:35 +02004232 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004233 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004234
Mathias Agopian74d211a2013-04-22 16:55:35 +02004235 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004236 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004237
4238 /*
4239 * VSYNC state
4240 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004241 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004242 result.append("\n");
4243
4244 /*
4245 * HWC layer minidump
4246 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004247 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004248 const int32_t displayId = display->getId();
4249 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004250 continue;
4251 }
4252
Dominik Laskowski7e045462018-05-30 13:02:02 -07004253 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004254 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004255 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004256 result.append("\n");
4257 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004258
4259 /*
4260 * Dump HWComposer state
4261 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004262 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004263 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004264 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004265 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004266 result.appendFormat(" h/w composer %s\n",
4267 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004268 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004269
4270 /*
4271 * Dump gralloc state
4272 */
4273 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4274 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004275
4276 /*
4277 * Dump VrFlinger state if in use.
4278 */
4279 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4280 result.append("VrFlinger state:\n");
4281 result.append(mVrFlinger->Dump().c_str());
4282 result.append("\n");
4283 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004284}
4285
Dominik Laskowski7e045462018-05-30 13:02:02 -07004286const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004287 // Note: mStateLock is held here
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004288 wp<IBinder> displayToken;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004289 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004290 if (display->getId() == displayId) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004291 displayToken = token;
Jesse Hall48bc05b2013-03-21 14:06:52 -07004292 break;
4293 }
4294 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004295 if (displayToken == nullptr) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004296 ALOGE("getLayerSortedByZForHwcDisplay: Invalid display %d", displayId);
Jesse Hall48bc05b2013-03-21 14:06:52 -07004297 // Just use the primary display so we have something to return
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004298 displayToken = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
Jesse Hall48bc05b2013-03-21 14:06:52 -07004299 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004300 return getDisplayDeviceLocked(displayToken)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004301}
4302
Keun young Park63f165f2012-08-31 10:53:36 -07004303bool SurfaceFlinger::startDdmConnection()
4304{
4305 void* libddmconnection_dso =
4306 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4307 if (!libddmconnection_dso) {
4308 return false;
4309 }
4310 void (*DdmConnection_start)(const char* name);
4311 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004312 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004313 if (!DdmConnection_start) {
4314 dlclose(libddmconnection_dso);
4315 return false;
4316 }
4317 (*DdmConnection_start)(getServiceName());
4318 return true;
4319}
4320
Chia-I Wu28f320b2018-05-03 11:02:56 -07004321void SurfaceFlinger::updateColorMatrixLocked() {
4322 mat4 colorMatrix;
4323 if (mGlobalSaturationFactor != 1.0f) {
4324 // Rec.709 luma coefficients
4325 float3 luminance{0.213f, 0.715f, 0.072f};
4326 luminance *= 1.0f - mGlobalSaturationFactor;
4327 mat4 saturationMatrix = mat4(
4328 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4329 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4330 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4331 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4332 );
4333 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4334 } else {
4335 colorMatrix = mClientColorMatrix * mDaltonizer();
4336 }
4337
4338 if (mCurrentState.colorMatrix != colorMatrix) {
4339 mCurrentState.colorMatrix = colorMatrix;
4340 mCurrentState.colorMatrixChanged = true;
4341 setTransactionFlags(eTransactionNeeded);
4342 }
4343}
4344
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004345status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004346 switch (code) {
4347 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004348 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004349 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004350 case CLEAR_ANIMATION_FRAME_STATS:
4351 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004352 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004353 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004354 case ENABLE_VSYNC_INJECTIONS:
4355 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004356 {
4357 // codes that require permission check
4358 IPCThreadState* ipc = IPCThreadState::self();
4359 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004360 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004361 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004362 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004363 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004364 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004365 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004366 break;
4367 }
Robert Carr1db73f62016-12-21 12:58:51 -08004368 /*
4369 * Calling setTransactionState is safe, because you need to have been
4370 * granted a reference to Client* and Handle* to do anything with it.
4371 *
4372 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4373 */
4374 case SET_TRANSACTION_STATE:
4375 case CREATE_SCOPED_CONNECTION:
4376 {
4377 return OK;
4378 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004379 case CAPTURE_SCREEN:
4380 {
4381 // codes that require permission check
4382 IPCThreadState* ipc = IPCThreadState::self();
4383 const int pid = ipc->getCallingPid();
4384 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004385 if ((uid != AID_GRAPHICS) &&
4386 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004387 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004388 return PERMISSION_DENIED;
4389 }
4390 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004391 }
chaviwa76b2712017-09-20 12:02:26 -07004392 case CAPTURE_LAYERS: {
4393 IPCThreadState* ipc = IPCThreadState::self();
4394 const int pid = ipc->getCallingPid();
4395 const int uid = ipc->getCallingUid();
4396 if ((uid != AID_GRAPHICS) &&
4397 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4398 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4399 return PERMISSION_DENIED;
4400 }
4401 break;
4402 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004403 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004404 return OK;
4405}
4406
4407status_t SurfaceFlinger::onTransact(
4408 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4409{
4410 status_t credentialCheck = CheckTransactCodeCredentials(code);
4411 if (credentialCheck != OK) {
4412 return credentialCheck;
4413 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004414
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004415 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4416 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004417 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004418 IPCThreadState* ipc = IPCThreadState::self();
4419 const int uid = ipc->getCallingUid();
4420 if (CC_UNLIKELY(uid != AID_SYSTEM
4421 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004422 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004423 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004424 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004425 return PERMISSION_DENIED;
4426 }
4427 int n;
4428 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004429 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004430 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004431 return NO_ERROR;
4432 case 1002: // SHOW_UPDATES
4433 n = data.readInt32();
4434 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004435 invalidateHwcGeometry();
4436 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004437 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004438 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004439 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004440 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004441 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004442 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004443 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004444 setTransactionFlags(
4445 eTransactionNeeded|
4446 eDisplayTransactionNeeded|
4447 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004448 return NO_ERROR;
4449 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004450 case 1006:{ // send empty update
4451 signalRefresh();
4452 return NO_ERROR;
4453 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004454 case 1008: // toggle use of hw composer
4455 n = data.readInt32();
4456 mDebugDisableHWC = n ? 1 : 0;
4457 invalidateHwcGeometry();
4458 repaintEverything();
4459 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004460 case 1009: // toggle use of transform hint
4461 n = data.readInt32();
4462 mDebugDisableTransformHint = n ? 1 : 0;
4463 invalidateHwcGeometry();
4464 repaintEverything();
4465 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004466 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004467 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004468 reply->writeInt32(0);
4469 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004470 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004471 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004472 return NO_ERROR;
4473 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004474 const auto display = getDefaultDisplayDevice();
4475 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004476 return NO_ERROR;
4477 }
4478 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004479 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004480 // daltonize
4481 n = data.readInt32();
4482 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004483 case 1:
4484 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4485 break;
4486 case 2:
4487 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4488 break;
4489 case 3:
4490 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4491 break;
4492 default:
4493 mDaltonizer.setType(ColorBlindnessType::None);
4494 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004495 }
4496 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004497 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004498 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004499 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004500 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004501
4502 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004503 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004504 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004505 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004506 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004507 // apply a color matrix
4508 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004509 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004510 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004511 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004512 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004513 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004514 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004515 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004516 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004517 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004518 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004519
4520 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4521 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004522 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004523 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4524 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4525 }
4526
Chia-I Wu28f320b2018-05-03 11:02:56 -07004527 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004528 return NO_ERROR;
4529 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004530 // This is an experimental interface
4531 // Needs to be shifted to proper binder interface when we productize
4532 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004533 n = data.readInt32();
4534 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004535 return NO_ERROR;
4536 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004537 case 1017: {
4538 n = data.readInt32();
4539 mForceFullDamage = static_cast<bool>(n);
4540 return NO_ERROR;
4541 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004542 case 1018: { // Modify Choreographer's phase offset
4543 n = data.readInt32();
4544 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4545 return NO_ERROR;
4546 }
4547 case 1019: { // Modify SurfaceFlinger's phase offset
4548 n = data.readInt32();
4549 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4550 return NO_ERROR;
4551 }
Irvel468051e2016-06-13 16:44:44 -07004552 case 1020: { // Layer updates interceptor
4553 n = data.readInt32();
4554 if (n) {
4555 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004556 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004557 }
4558 else{
4559 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004560 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004561 }
4562 return NO_ERROR;
4563 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004564 case 1021: { // Disable HWC virtual displays
4565 n = data.readInt32();
4566 mUseHwcVirtualDisplays = !n;
4567 return NO_ERROR;
4568 }
Romain Guy0147a172017-06-01 13:53:56 -07004569 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004570 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004571 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004572
Chia-I Wu28f320b2018-05-03 11:02:56 -07004573 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004574 return NO_ERROR;
4575 }
Romain Guy54f154a2017-10-24 21:40:32 +01004576 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004577 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004578 invalidateHwcGeometry();
4579 repaintEverything();
4580 return NO_ERROR;
4581 }
4582 case 1024: { // Is wide color gamut rendering/color management supported?
4583 reply->writeBool(hasWideColorDisplay);
4584 return NO_ERROR;
4585 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004586 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004587 n = data.readInt32();
4588 if (n) {
4589 ALOGV("LayerTracing enabled");
4590 mTracing.enable();
4591 doTracing("tracing.enable");
4592 reply->writeInt32(NO_ERROR);
4593 } else {
4594 ALOGV("LayerTracing disabled");
4595 status_t err = mTracing.disable();
4596 reply->writeInt32(err);
4597 }
4598 return NO_ERROR;
4599 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004600 case 1026: { // Get layer tracing status
4601 reply->writeBool(mTracing.isEnabled());
4602 return NO_ERROR;
4603 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004604 // Is a DisplayColorSetting supported?
4605 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004606 const auto display = getDefaultDisplayDevice();
4607 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004608 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004609 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004610
4611 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4612 switch (setting) {
4613 case DisplayColorSetting::MANAGED:
4614 reply->writeBool(hasWideColorDisplay);
4615 break;
4616 case DisplayColorSetting::UNMANAGED:
4617 reply->writeBool(true);
4618 break;
4619 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004620 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004621 break;
4622 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004623 reply->writeBool(
4624 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004625 break;
4626 }
4627 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004628 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004629 // Is VrFlinger active?
4630 case 1028: {
4631 Mutex::Autolock _l(mStateLock);
4632 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4633 return NO_ERROR;
4634 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004635 }
4636 }
4637 return err;
4638}
4639
Steven Thomas6d8110b2017-08-31 18:24:21 -07004640void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004641 android_atomic_or(1, &mRepaintEverything);
4642 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004643}
4644
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004645// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4646class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004647public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004648 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4649 ~WindowDisconnector() {
4650 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004651 }
4652
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004653private:
4654 ANativeWindow* mWindow;
4655 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004656};
4657
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004658status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4659 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4660 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4661 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004662 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004663 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004664
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004665 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004666
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004667 const auto display = getDisplayDeviceLocked(displayToken);
4668 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004669
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004670 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004671
4672 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004673 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004674 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004675}
4676
4677status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004678 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004679 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004680 ATRACE_CALL();
4681
4682 class LayerRenderArea : public RenderArea {
4683 public:
Robert Carr578038f2018-03-09 12:25:24 -08004684 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4685 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004686 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004687 mLayer(layer),
4688 mCrop(crop),
4689 mFlinger(flinger),
4690 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004691 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004692 Rect getBounds() const override {
4693 const Layer::State& layerState(mLayer->getDrawingState());
4694 return Rect(layerState.active.w, layerState.active.h);
4695 }
4696 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4697 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4698 bool isSecure() const override { return false; }
4699 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004700 Rect getSourceCrop() const override {
4701 if (mCrop.isEmpty()) {
4702 return getBounds();
4703 } else {
4704 return mCrop;
4705 }
4706 }
Robert Carr578038f2018-03-09 12:25:24 -08004707 class ReparentForDrawing {
4708 public:
4709 const sp<Layer>& oldParent;
4710 const sp<Layer>& newParent;
4711
4712 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4713 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004714 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004715 }
Robert Carr15eae092018-03-23 13:43:53 -07004716 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004717 };
4718
4719 void render(std::function<void()> drawLayers) override {
4720 if (!mChildrenOnly) {
4721 mTransform = mLayer->getTransform().inverse();
4722 drawLayers();
4723 } else {
4724 Rect bounds = getBounds();
4725 screenshotParentLayer =
4726 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4727 bounds.getWidth(), bounds.getHeight(), 0);
4728
4729 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4730 drawLayers();
4731 }
4732 }
chaviwa76b2712017-09-20 12:02:26 -07004733
chaviwa76b2712017-09-20 12:02:26 -07004734 private:
chaviw7206d492017-11-10 16:16:12 -08004735 const sp<Layer> mLayer;
4736 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004737
4738 // In the "childrenOnly" case we reparent the children to a screenshot
4739 // layer which has no properties set and which does not draw.
4740 sp<ContainerLayer> screenshotParentLayer;
4741 Transform mTransform;
4742
4743 SurfaceFlinger* mFlinger;
4744 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004745 };
4746
4747 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4748 auto parent = layerHandle->owner.promote();
4749
chaviw7206d492017-11-10 16:16:12 -08004750 if (parent == nullptr || parent->isPendingRemoval()) {
4751 ALOGE("captureLayers called with a removed parent");
4752 return NAME_NOT_FOUND;
4753 }
4754
Robert Carr578038f2018-03-09 12:25:24 -08004755 const int uid = IPCThreadState::self()->getCallingUid();
4756 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4757 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4758 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4759 return PERMISSION_DENIED;
4760 }
4761
chaviw7206d492017-11-10 16:16:12 -08004762 Rect crop(sourceCrop);
4763 if (sourceCrop.width() <= 0) {
4764 crop.left = 0;
4765 crop.right = parent->getCurrentState().active.w;
4766 }
4767
4768 if (sourceCrop.height() <= 0) {
4769 crop.top = 0;
4770 crop.bottom = parent->getCurrentState().active.h;
4771 }
4772
4773 int32_t reqWidth = crop.width() * frameScale;
4774 int32_t reqHeight = crop.height() * frameScale;
4775
Robert Carr578038f2018-03-09 12:25:24 -08004776 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004777
Robert Carr578038f2018-03-09 12:25:24 -08004778 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004779 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4780 if (!layer->isVisible()) {
4781 return;
Robert Carr578038f2018-03-09 12:25:24 -08004782 } else if (childrenOnly && layer == parent.get()) {
4783 return;
chaviwa76b2712017-09-20 12:02:26 -07004784 }
4785 visitor(layer);
4786 });
4787 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004788 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004789}
4790
4791status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4792 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004793 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004794 bool useIdentityTransform) {
4795 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004796
Iris Chang7501ed62018-04-30 14:45:42 +08004797 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004798
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004799 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4800 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4801 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4802 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004803
4804 // This mutex protects syncFd and captureResult for communication of the return values from the
4805 // main thread back to this Binder thread
4806 std::mutex captureMutex;
4807 std::condition_variable captureCondition;
4808 std::unique_lock<std::mutex> captureLock(captureMutex);
4809 int syncFd = -1;
4810 std::optional<status_t> captureResult;
4811
Robert Carr03480e22018-01-04 16:02:06 -08004812 const int uid = IPCThreadState::self()->getCallingUid();
4813 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4814
Dominik Laskowski8c001672018-05-30 16:52:06 -07004815 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004816 // If there is a refresh pending, bug out early and tell the binder thread to try again
4817 // after the refresh.
4818 if (mRefreshPending) {
4819 ATRACE_NAME("Skipping screenshot for now");
4820 std::unique_lock<std::mutex> captureLock(captureMutex);
4821 captureResult = std::make_optional<status_t>(EAGAIN);
4822 captureCondition.notify_one();
4823 return;
4824 }
4825
4826 status_t result = NO_ERROR;
4827 int fd = -1;
4828 {
4829 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07004830 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08004831 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4832 useIdentityTransform, forSystem, &fd);
4833 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004834 }
4835
4836 {
4837 std::unique_lock<std::mutex> captureLock(captureMutex);
4838 syncFd = fd;
4839 captureResult = std::make_optional<status_t>(result);
4840 captureCondition.notify_one();
4841 }
4842 });
4843
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004844 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004845 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004846 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004847 while (*captureResult == EAGAIN) {
4848 captureResult.reset();
4849 result = postMessageAsync(message);
4850 if (result != NO_ERROR) {
4851 return result;
4852 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07004853 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004854 }
4855 result = *captureResult;
4856 }
4857
4858 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004859 sync_wait(syncFd, -1);
4860 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004861 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004862
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004863 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004864}
4865
chaviwa76b2712017-09-20 12:02:26 -07004866void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4867 TraverseLayersFunction traverseLayers, bool yswap,
4868 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004869 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004870
Lloyd Pique144e1162017-12-20 16:44:52 -08004871 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004872
4873 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004874 const auto raWidth = renderArea.getWidth();
4875 const auto raHeight = renderArea.getHeight();
4876
4877 const auto reqWidth = renderArea.getReqWidth();
4878 const auto reqHeight = renderArea.getReqHeight();
4879 Rect sourceCrop = renderArea.getSourceCrop();
4880
Iris Chang7501ed62018-04-30 14:45:42 +08004881 bool filtering = false;
4882 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4883 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
4884 static_cast<int32_t>(reqHeight) != raWidth;
4885 } else {
4886 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4887 static_cast<int32_t>(reqHeight) != raHeight;
4888 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004889
Dan Stozac1879002014-05-22 15:59:05 -07004890 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004891 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004892 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004893 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08004894 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4895 Transform tr;
4896 uint32_t flags = 0x00;
4897 switch (mPrimaryDisplayOrientation) {
4898 case DisplayState::eOrientation90:
4899 flags = Transform::ROT_90;
4900 break;
4901 case DisplayState::eOrientation180:
4902 flags = Transform::ROT_180;
4903 break;
4904 case DisplayState::eOrientation270:
4905 flags = Transform::ROT_270;
4906 break;
4907 }
4908 tr.set(flags, raWidth, raHeight);
4909 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07004910 }
4911
4912 // ensure that sourceCrop is inside screen
4913 if (sourceCrop.left < 0) {
4914 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4915 }
chaviwa76b2712017-09-20 12:02:26 -07004916 if (sourceCrop.right > raWidth) {
4917 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004918 }
4919 if (sourceCrop.top < 0) {
4920 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4921 }
chaviwa76b2712017-09-20 12:02:26 -07004922 if (sourceCrop.bottom > raHeight) {
4923 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004924 }
4925
Chia-I Wu36574d92018-05-16 10:54:36 -07004926 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
4927 engine.setOutputDataSpace(Dataspace::SRGB);
4928 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07004929
Mathias Agopian180f10d2013-04-10 22:55:41 -07004930 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004931 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004932
Iris Chang7501ed62018-04-30 14:45:42 +08004933 Transform::orientation_flags rotation = renderArea.getRotationFlags();
4934 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4935 // convert hw orientation into flag presentation
4936 // here inverse transform needed
4937 uint8_t hw_rot_90 = 0x00;
4938 uint8_t hw_flip_hv = 0x00;
4939 switch (mPrimaryDisplayOrientation) {
4940 case DisplayState::eOrientation90:
4941 hw_rot_90 = Transform::ROT_90;
4942 hw_flip_hv = Transform::ROT_180;
4943 break;
4944 case DisplayState::eOrientation180:
4945 hw_flip_hv = Transform::ROT_180;
4946 break;
4947 case DisplayState::eOrientation270:
4948 hw_rot_90 = Transform::ROT_90;
4949 break;
4950 }
4951
4952 // transform flags operation
4953 // 1) flip H V if both have ROT_90 flag
4954 // 2) XOR these flags
4955 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
4956 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
4957 if (rotation_rot_90 & hw_rot_90) {
4958 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
4959 }
4960 rotation = static_cast<Transform::orientation_flags>
4961 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
4962 }
4963
Mathias Agopian180f10d2013-04-10 22:55:41 -07004964 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004965 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08004966 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004967 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004968
chaviw50da5042018-04-09 13:49:37 -07004969 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004970 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004971 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004972
chaviwa76b2712017-09-20 12:02:26 -07004973 traverseLayers([&](Layer* layer) {
4974 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07004975 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004976 if (filtering) layer->setFiltering(false);
4977 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004978}
4979
chaviwa76b2712017-09-20 12:02:26 -07004980status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4981 TraverseLayersFunction traverseLayers,
4982 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004983 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004984 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004985 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004986 ATRACE_CALL();
4987
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004988 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004989
4990 traverseLayers([&](Layer* layer) {
4991 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4992 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004993
Robert Carr03480e22018-01-04 16:02:06 -08004994 // We allow the system server to take screenshots of secure layers for
4995 // use in situations like the Screen-rotation animation and place
4996 // the impetus on WindowManager to not persist them.
4997 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004998 ALOGW("FB is protected: PERMISSION_DENIED");
4999 return PERMISSION_DENIED;
5000 }
5001
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005002 // this binds the given EGLImage as a framebuffer for the
5003 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005004 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005005 if (bufferBond.getStatus() != NO_ERROR) {
5006 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005007 return INVALID_OPERATION;
5008 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005009
Dan Stozaabcda352017-06-01 14:37:39 -07005010 // this will in fact render into our dequeued buffer
5011 // via an FBO, which means we didn't have to create
5012 // an EGLSurface and therefore we're not
5013 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005014 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005015
Dan Stozaabcda352017-06-01 14:37:39 -07005016 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005017 getRenderEngine().finish();
5018 *outSyncFd = -1;
5019
chaviwa76b2712017-09-20 12:02:26 -07005020 const auto reqWidth = renderArea.getReqWidth();
5021 const auto reqHeight = renderArea.getReqHeight();
5022
Dan Stozaabcda352017-06-01 14:37:39 -07005023 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5024 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005025 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005026 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005027 } else {
5028 base::unique_fd syncFd = getRenderEngine().flush();
5029 if (syncFd < 0) {
5030 getRenderEngine().finish();
5031 }
5032 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005033 }
5034
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005035 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005036}
5037
Mathias Agopiand5556842013-09-19 17:08:37 -07005038void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005039 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005040 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005041 for (size_t y = 0; y < h; y++) {
5042 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5043 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005044 if (p[x] != 0xFF000000) return;
5045 }
5046 }
chaviwa76b2712017-09-20 12:02:26 -07005047 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005048
Robert Carr2047fae2016-11-28 14:09:09 -08005049 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005050 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005051 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005052 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5053 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5054 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5055 static_cast<float>(state.color.a));
5056 i++;
5057 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005058 }
5059}
5060
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005061// ---------------------------------------------------------------------------
5062
Dan Stoza412903f2017-04-27 13:42:17 -07005063void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5064 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005065}
5066
Dan Stoza412903f2017-04-27 13:42:17 -07005067void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5068 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005069}
5070
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005071void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5072 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005073 const LayerVector::Visitor& visitor) {
5074 // We loop through the first level of layers without traversing,
5075 // as we need to interpret min/max layer Z in the top level Z space.
5076 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005077 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005078 continue;
5079 }
5080 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005081 // relative layers are traversed in Layer::traverseInZOrder
5082 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005083 continue;
5084 }
5085 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005086 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005087 return;
5088 }
chaviwa76b2712017-09-20 12:02:26 -07005089 if (!layer->isVisible()) {
5090 return;
5091 }
5092 visitor(layer);
5093 });
5094 }
5095}
5096
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005097}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005098
Chia-I Wu30505fb2018-03-26 16:20:31 -07005099
Mathias Agopian3f844832013-08-07 21:24:32 -07005100#if defined(__gl_h_)
5101#error "don't include gl/gl.h in this file"
5102#endif
5103
5104#if defined(__gl2_h_)
5105#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005106#endif