blob: 4730b7997a456cfe3456fdb470c4ab36c50d4446 [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
Thierry Strudel2924d012017-08-14 15:19:37 -0700486 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700487 readPersistentProperties();
488 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700489 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800490}
491
Mathias Agopian3f844832013-08-07 21:24:32 -0700492void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700493 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800494 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700495 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700496 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800497 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
498 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700499 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700500 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700501 return true;
502 }
503 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700504 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700505}
506
Lloyd Piquee83f9312018-02-01 12:53:17 -0800507class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700508public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700509 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000510 const char* name) :
511 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700512 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700513 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000514 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
515 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700516 mDispSync(dispSync),
517 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700518 mVsyncMutex(),
519 mPhaseOffset(phaseOffset),
520 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700521
Lloyd Piquee83f9312018-02-01 12:53:17 -0800522 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700523
Lloyd Piquee83f9312018-02-01 12:53:17 -0800524 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700525 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700526 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000527 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700528 static_cast<DispSync::Callback*>(this));
529 if (err != NO_ERROR) {
530 ALOGE("error registering vsync callback: %s (%d)",
531 strerror(-err), err);
532 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700533 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534 } else {
535 status_t err = mDispSync->removeEventListener(
536 static_cast<DispSync::Callback*>(this));
537 if (err != NO_ERROR) {
538 ALOGE("error unregistering vsync callback: %s (%d)",
539 strerror(-err), err);
540 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700541 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700543 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700544 }
545
Lloyd Piquee83f9312018-02-01 12:53:17 -0800546 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700547 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700548 mCallback = callback;
549 }
550
Lloyd Piquee83f9312018-02-01 12:53:17 -0800551 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700552 Mutex::Autolock lock(mVsyncMutex);
553
554 // Normalize phaseOffset to [0, period)
555 auto period = mDispSync->getPeriod();
556 phaseOffset %= period;
557 if (phaseOffset < 0) {
558 // If we're here, then phaseOffset is in (-period, 0). After this
559 // operation, it will be in (0, period)
560 phaseOffset += period;
561 }
562 mPhaseOffset = phaseOffset;
563
564 // If we're not enabled, we don't need to mess with the listeners
565 if (!mEnabled) {
566 return;
567 }
568
Dan Stoza84d619e2018-03-28 17:07:36 -0700569 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
570 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700571 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700572 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700573 strerror(-err), err);
574 }
575 }
576
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577private:
578 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800579 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700580 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700581 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700582 callback = mCallback;
583
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700584 if (mTraceVsync) {
585 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700586 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700587 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588 }
589
Peiyong Lin566a3b42018-01-09 18:22:43 -0800590 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700591 callback->onVSyncEvent(when);
592 }
593 }
594
Tim Murray4a4e4a22016-04-19 16:29:23 +0000595 const char* const mName;
596
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700597 int mValue;
598
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700599 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700600 const String8 mVsyncOnLabel;
601 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700602
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700603 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700604
605 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800606 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700607
608 Mutex mVsyncMutex; // Protects the following
609 nsecs_t mPhaseOffset;
610 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700611};
612
Lloyd Piquee83f9312018-02-01 12:53:17 -0800613class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700614public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800615 InjectVSyncSource() = default;
616 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700617
Lloyd Piquee83f9312018-02-01 12:53:17 -0800618 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700619 std::lock_guard<std::mutex> lock(mCallbackMutex);
620 mCallback = callback;
621 }
622
Lloyd Piquee83f9312018-02-01 12:53:17 -0800623 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700624 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700625 if (mCallback) {
626 mCallback->onVSyncEvent(when);
627 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700628 }
629
Lloyd Piquee83f9312018-02-01 12:53:17 -0800630 void setVSyncEnabled(bool) override {}
631 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700632
633private:
634 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800635 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700636};
637
Wei Wangf9b05ee2017-07-19 20:59:39 -0700638// Do not call property_set on main thread which will be blocked by init
639// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700640void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700641 ALOGI( "SurfaceFlinger's main thread ready to run. "
642 "Initializing graphics H/W...");
643
Thierry Strudel2924d012017-08-14 15:19:37 -0700644 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900645
Steven Thomasb02664d2017-07-26 18:48:28 -0700646 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800647
Steven Thomasb02664d2017-07-26 18:48:28 -0700648 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800649 mEventThreadSource =
650 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
651 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800652 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
653 [this]() { resyncWithRateLimit(); },
654 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800655 "appEventThread");
656 mSfEventThreadSource =
657 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
658 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800659
Lloyd Pique24b0a482018-03-09 18:52:26 -0800660 mSFEventThread =
661 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
662 [this]() { resyncWithRateLimit(); },
663 [this](nsecs_t timestamp) {
664 mInterceptor->saveVSyncEvent(timestamp);
665 },
666 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800667 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza84d619e2018-03-28 17:07:36 -0700668 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800669
Steven Thomasb02664d2017-07-26 18:48:28 -0700670 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800671 getBE().mRenderEngine =
672 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
673 hasWideColorDisplay
674 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
675 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800676 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700677
678 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
679 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800680 getBE().mHwc.reset(
681 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700682 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800683 // Process any initial hotplug and resulting display changes.
684 processDisplayHotplugEventsLocked();
685 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
686 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800687
Lloyd Piquefcd86612017-12-14 17:15:36 -0800688 // make the default display GLContext current so that we can create textures
689 // when creating Layers (which may happens before we render something)
690 getDefaultDisplayDeviceLocked()->makeCurrent();
691
Steven Thomas050b2c82017-03-06 11:45:16 -0800692 if (useVrFlinger) {
693 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700694 // This callback is called from the vr flinger dispatch thread. We
695 // need to call signalTransaction(), which requires holding
696 // mStateLock when we're not on the main thread. Acquiring
697 // mStateLock from the vr flinger dispatch thread might trigger a
698 // deadlock in surface flinger (see b/66916578), so post a message
699 // to be handled on the main thread instead.
700 sp<LambdaMessage> message = new LambdaMessage([=]() {
701 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
702 mVrFlingerRequestsDisplay = requestDisplay;
703 signalTransaction();
704 });
705 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800706 };
David Sodman105b7dc2017-11-04 20:28:14 -0700707 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
708 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800709 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800710 if (!mVrFlinger) {
711 ALOGE("Failed to start vrflinger");
712 }
713 }
714
Lloyd Pique379adc12018-01-22 17:31:47 -0800715 mEventControlThread = std::make_unique<impl::EventControlThread>(
716 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700717
Mathias Agopian92a979a2012-08-02 18:32:23 -0700718 // initialize our drawing state
719 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700720
Andy McFadden13a082e2012-08-24 10:16:42 -0700721 // set initial conditions (e.g. unblank default device)
722 initializeDisplays();
723
David Sodmanbc815282017-11-05 18:57:52 -0800724 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700725
Wei Wangf9b05ee2017-07-19 20:59:39 -0700726 // Inform native graphics APIs whether the present timestamp is supported:
727 if (getHwComposer().hasCapability(
728 HWC2::Capability::PresentFenceIsNotReliable)) {
729 mStartPropertySetThread = new StartPropertySetThread(false);
730 } else {
731 mStartPropertySetThread = new StartPropertySetThread(true);
732 }
733
734 if (mStartPropertySetThread->Start() != NO_ERROR) {
735 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800736 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800737
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800738 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
739 Dataspace::SRGB_LINEAR);
740
Dan Stoza9e56aa02015-11-02 13:00:03 -0800741 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700742}
743
Romain Guy11d63f42017-07-20 12:47:14 -0700744void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700745 Mutex::Autolock _l(mStateLock);
746
Romain Guy11d63f42017-07-20 12:47:14 -0700747 char value[PROPERTY_VALUE_MAX];
748
749 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800750 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700751 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800752 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100753
754 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700755 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700756}
757
Mathias Agopiana67e4182012-06-19 17:26:12 -0700758void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800759 // Start boot animation service by setting a property mailbox
760 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700761 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800762 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700763 if (mStartPropertySetThread->join() != NO_ERROR) {
764 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800765 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700766}
767
Mathias Agopian875d8e12013-06-07 15:35:48 -0700768size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800769 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700770}
771
Mathias Agopian875d8e12013-06-07 15:35:48 -0700772size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800773 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700774}
775
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800776// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800777
Jamie Gennis582270d2011-08-17 18:19:00 -0700778bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800779 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800780 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800781 return authenticateSurfaceTextureLocked(bufferProducer);
782}
783
784bool SurfaceFlinger::authenticateSurfaceTextureLocked(
785 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800786 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800787 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800788}
789
Brian Anderson6b376712017-04-04 10:51:39 -0700790status_t SurfaceFlinger::getSupportedFrameTimestamps(
791 std::vector<FrameEvent>* outSupported) const {
792 *outSupported = {
793 FrameEvent::REQUESTED_PRESENT,
794 FrameEvent::ACQUIRE,
795 FrameEvent::LATCH,
796 FrameEvent::FIRST_REFRESH_START,
797 FrameEvent::LAST_REFRESH_START,
798 FrameEvent::GPU_COMPOSITION_DONE,
799 FrameEvent::DEQUEUE_READY,
800 FrameEvent::RELEASE,
801 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700802 ConditionalLock _l(mStateLock,
803 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700804 if (!getHwComposer().hasCapability(
805 HWC2::Capability::PresentFenceIsNotReliable)) {
806 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
807 }
808 return NO_ERROR;
809}
810
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700811status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
812 Vector<DisplayInfo>* configs) {
813 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700814 return BAD_VALUE;
815 }
816
Jesse Hall692c7232012-11-08 15:41:56 -0800817 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700818 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
819 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700820 type = i;
821 break;
822 }
823 }
824
825 if (type < 0) {
826 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700827 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 // TODO: Not sure if display density should handled by SF any longer
830 class Density {
831 static int getDensityFromProperty(char const* propName) {
832 char property[PROPERTY_VALUE_MAX];
833 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800834 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 density = atoi(property);
836 }
837 return density;
838 }
839 public:
840 static int getEmuDensity() {
841 return getDensityFromProperty("qemu.sf.lcd_density"); }
842 static int getBuildDensity() {
843 return getDensityFromProperty("ro.sf.lcd_density"); }
844 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700845
Dan Stoza7f7da322014-05-02 15:26:25 -0700846 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700847
Steven Thomas6d8110b2017-08-31 18:24:21 -0700848 ConditionalLock _l(mStateLock,
849 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700851 DisplayInfo info = DisplayInfo();
852
Dan Stoza9e56aa02015-11-02 13:00:03 -0800853 float xdpi = hwConfig->getDpiX();
854 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700855
856 if (type == DisplayDevice::DISPLAY_PRIMARY) {
857 // The density of the device is provided by a build property
858 float density = Density::getBuildDensity() / 160.0f;
859 if (density == 0) {
860 // the build doesn't provide a density -- this is wrong!
861 // use xdpi instead
862 ALOGE("ro.sf.lcd_density must be defined as a build property");
863 density = xdpi / 160.0f;
864 }
865 if (Density::getEmuDensity()) {
866 // if "qemu.sf.lcd_density" is specified, it overrides everything
867 xdpi = ydpi = density = Density::getEmuDensity();
868 density /= 160.0f;
869 }
870 info.density = density;
871
872 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700873 const auto display = getDefaultDisplayDeviceLocked();
874 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 } else {
876 // TODO: where should this value come from?
877 static const int TV_DENSITY = 213;
878 info.density = TV_DENSITY / 160.0f;
879 info.orientation = 0;
880 }
881
Dan Stoza9e56aa02015-11-02 13:00:03 -0800882 info.w = hwConfig->getWidth();
883 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700884 info.xdpi = xdpi;
885 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900887 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888
Andy McFadden91b2ca82014-06-13 14:04:23 -0700889 // This is how far in advance a buffer must be queued for
890 // presentation at a given time. If you want a buffer to appear
891 // on the screen at time N, you must submit the buffer before
892 // (N - presentationDeadline).
893 //
894 // Normally it's one full refresh period (to give SF a chance to
895 // latch the buffer), but this can be reduced by configuring a
896 // DispSync offset. Any additional delays introduced by the hardware
897 // composer or panel must be accounted for here.
898 //
899 // We add an additional 1ms to allow for processing time and
900 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800901 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800902 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700903
904 // All non-virtual displays are currently considered secure.
905 info.secure = true;
906
Iris Chang7501ed62018-04-30 14:45:42 +0800907 if (type == DisplayDevice::DISPLAY_PRIMARY &&
908 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
909 std::swap(info.w, info.h);
910 }
911
Michael Wright28f24d02016-07-12 13:30:53 -0700912 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700913 }
914
Dan Stoza7f7da322014-05-02 15:26:25 -0700915 return NO_ERROR;
916}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
919 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700920 return BAD_VALUE;
921 }
922
923 // FIXME for now we always return stats for the primary display
924 memset(stats, 0, sizeof(*stats));
925 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
926 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
927 return NO_ERROR;
928}
929
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700930int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
931 const auto display = getDisplayDevice(displayToken);
932 if (!display) {
933 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800934 return BAD_VALUE;
935 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700936
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700937 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700938}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
941 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700942 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700943 return;
944 }
945
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700946 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700947 ALOGW("Trying to set config for virtual display");
948 return;
949 }
950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951 display->setActiveConfig(mode);
952 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700953}
954
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700955status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
956 postMessageSync(new LambdaMessage([&]() {
957 Vector<DisplayInfo> configs;
958 getDisplayConfigs(displayToken, &configs);
959 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
960 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
961 configs.size());
962 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700963 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700964 const auto display = getDisplayDevice(displayToken);
965 if (!display) {
966 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
967 displayToken.get());
968 } else if (display->isVirtual()) {
969 ALOGW("Attempt to set active config %d for virtual display", mode);
970 } else {
971 setActiveConfigInternal(display, mode);
972 }
973 }));
974
Mathias Agopian888c8222012-08-04 21:10:38 -0700975 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700976}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700977status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
978 Vector<ColorMode>* outColorModes) {
979 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700980 return BAD_VALUE;
981 }
982
Michael Wright28f24d02016-07-12 13:30:53 -0700983 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700984 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
985 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700986 type = i;
987 break;
988 }
989 }
990
991 if (type < 0) {
992 return type;
993 }
994
Peiyong Lina52f0292018-03-14 17:26:31 -0700995 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700996 {
997 ConditionalLock _l(mStateLock,
998 std::this_thread::get_id() != mMainThreadId);
999 modes = getHwComposer().getColorModes(type);
1000 }
Michael Wright28f24d02016-07-12 13:30:53 -07001001 outColorModes->clear();
1002 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1003
1004 return NO_ERROR;
1005}
1006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001007ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1008 if (const auto display = getDisplayDevice(displayToken)) {
1009 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001010 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001011 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001012}
1013
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001014void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1015 Dataspace dataSpace, RenderIntent renderIntent) {
1016 ColorMode currentMode = display->getActiveColorMode();
1017 Dataspace currentDataSpace = display->getCompositionDataSpace();
1018 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001019
Peiyong Lin38e9a562018-04-10 16:24:20 -07001020 if (mode == currentMode && dataSpace == currentDataSpace &&
1021 renderIntent == currentRenderIntent) {
1022 return;
1023 }
1024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001026 ALOGW("Trying to set config for virtual display");
1027 return;
1028 }
1029
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001030 display->setActiveColorMode(mode);
1031 display->setCompositionDataSpace(dataSpace);
1032 display->setActiveRenderIntent(renderIntent);
1033 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001034
1035 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001036 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1037 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001038}
1039
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001040status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
1041 postMessageSync(new LambdaMessage([&]() {
1042 Vector<ColorMode> modes;
1043 getDisplayColorModes(displayToken, &modes);
1044 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1045 if (mode < ColorMode::NATIVE || !exists) {
1046 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1047 decodeColorMode(mode).c_str(), mode, displayToken.get());
1048 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001049 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050 const auto display = getDisplayDevice(displayToken);
1051 if (!display) {
1052 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1053 decodeColorMode(mode).c_str(), mode, displayToken.get());
1054 } else if (display->isVirtual()) {
1055 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1056 decodeColorMode(mode).c_str(), mode);
1057 } else {
1058 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1059 RenderIntent::COLORIMETRIC);
1060 }
1061 }));
1062
Michael Wright28f24d02016-07-12 13:30:53 -07001063 return NO_ERROR;
1064}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001065
Svetoslavd85084b2014-03-20 10:28:31 -07001066status_t SurfaceFlinger::clearAnimationFrameStats() {
1067 Mutex::Autolock _l(mStateLock);
1068 mAnimFrameTracker.clearStats();
1069 return NO_ERROR;
1070}
1071
1072status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1073 Mutex::Autolock _l(mStateLock);
1074 mAnimFrameTracker.getStats(outStats);
1075 return NO_ERROR;
1076}
1077
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001078status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1079 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001080 Mutex::Autolock _l(mStateLock);
1081
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001082 const auto display = getDisplayDeviceLocked(displayToken);
1083 if (!display) {
1084 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001085 return BAD_VALUE;
1086 }
1087
Peiyong Linfb069302018-04-25 14:34:31 -07001088 // At this point the DisplayDeivce should already be set up,
1089 // meaning the luminance information is already queried from
1090 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001091 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001092 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1093 capabilities.getDesiredMaxLuminance(),
1094 capabilities.getDesiredMaxAverageLuminance(),
1095 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001096
1097 return NO_ERROR;
1098}
1099
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001100status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001101 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1102 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001103
Chia-I Wu90f669f2017-10-05 14:24:41 -07001104 if (mInjectVSyncs == enable) {
1105 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001106 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001107
1108 if (enable) {
1109 ALOGV("VSync Injections enabled");
1110 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001111 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001112 mInjectorEventThread = std::make_unique<
1113 impl::EventThread>(mVSyncInjector.get(),
1114 [this]() { resyncWithRateLimit(); },
1115 impl::EventThread::InterceptVSyncsCallback(),
1116 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001117 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001118 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001119 } else {
1120 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001121 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001122 }
1123
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001124 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001125 });
1126 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001127 return NO_ERROR;
1128}
1129
1130status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001131 Mutex::Autolock _l(mStateLock);
1132
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001133 if (!mInjectVSyncs) {
1134 ALOGE("VSync Injections not enabled");
1135 return BAD_VALUE;
1136 }
1137 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1138 ALOGV("Injecting VSync inside SurfaceFlinger");
1139 mVSyncInjector->onInjectSyncEvent(when);
1140 }
1141 return NO_ERROR;
1142}
1143
Lloyd Pique755e3192018-01-31 16:46:15 -08001144status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1145 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001146 IPCThreadState* ipc = IPCThreadState::self();
1147 const int pid = ipc->getCallingPid();
1148 const int uid = ipc->getCallingUid();
1149 if ((uid != AID_SHELL) &&
1150 !PermissionCache::checkPermission(sDump, pid, uid)) {
1151 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1152 return PERMISSION_DENIED;
1153 }
1154
1155 // Try to acquire a lock for 1s, fail gracefully
1156 const status_t err = mStateLock.timedLock(s2ns(1));
1157 const bool locked = (err == NO_ERROR);
1158 if (!locked) {
1159 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1160 return TIMED_OUT;
1161 }
1162
1163 outLayers->clear();
1164 mCurrentState.traverseInZOrder([&](Layer* layer) {
1165 outLayers->push_back(layer->getLayerDebugInfo());
1166 });
1167
1168 mStateLock.unlock();
1169 return NO_ERROR;
1170}
1171
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001172// ----------------------------------------------------------------------------
1173
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001174sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1175 ISurfaceComposer::VsyncSource vsyncSource) {
1176 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1177 return mSFEventThread->createEventConnection();
1178 } else {
1179 return mEventThread->createEventConnection();
1180 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001181}
1182
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001183// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001184
1185void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001186 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001187}
1188
1189void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001190 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001191}
1192
1193void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001194 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001195}
1196
1197void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001198 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001199 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001200}
1201
1202status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001203 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001204 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001205}
1206
1207status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001208 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001209 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001210 if (res == NO_ERROR) {
1211 msg->wait();
1212 }
1213 return res;
1214}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001215
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001216void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001217 do {
1218 waitForEvent();
1219 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001220}
1221
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001222void SurfaceFlinger::enableHardwareVsync() {
1223 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001224 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001226 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1227 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001229 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001230}
1231
Jesse Hall948fe0c2013-10-14 12:56:09 -07001232void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233 Mutex::Autolock _l(mHWVsyncLock);
1234
Jesse Hall948fe0c2013-10-14 12:56:09 -07001235 if (makeAvailable) {
1236 mHWVsyncAvailable = true;
1237 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001238 // Hardware vsync is not currently available, so abort the resync
1239 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001240 return;
1241 }
1242
David Sodman105b7dc2017-11-04 20:28:14 -07001243 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001244 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001245
1246 mPrimaryDispSync.reset();
1247 mPrimaryDispSync.setPeriod(period);
1248
1249 if (!mPrimaryHWVsyncEnabled) {
1250 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001251 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1252 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001253 mPrimaryHWVsyncEnabled = true;
1254 }
1255}
1256
Jesse Hall948fe0c2013-10-14 12:56:09 -07001257void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001258 Mutex::Autolock _l(mHWVsyncLock);
1259 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001260 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1261 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262 mPrimaryDispSync.endResync();
1263 mPrimaryHWVsyncEnabled = false;
1264 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001265 if (makeUnavailable) {
1266 mHWVsyncAvailable = false;
1267 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001268}
1269
Tim Murray4a4e4a22016-04-19 16:29:23 +00001270void SurfaceFlinger::resyncWithRateLimit() {
1271 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001272
1273 // No explicit locking is needed here since EventThread holds a lock while calling this method
1274 static nsecs_t sLastResyncAttempted = 0;
1275 const nsecs_t now = systemTime();
1276 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001277 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001278 }
Dan Stoza57164302017-05-08 14:03:54 -07001279 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001280}
1281
Steven Thomasb02664d2017-07-26 18:48:28 -07001282void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1283 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001284 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001285 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001286 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001287 return;
1288 }
1289
1290 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001291 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001292 return;
1293 }
1294
Jamie Gennisd1700752013-10-14 12:22:52 -07001295 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296
Jamie Gennisd1700752013-10-14 12:22:52 -07001297 { // Scope for the lock
1298 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001299 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001300 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001301 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001302 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001303
1304 if (needsHwVsync) {
1305 enableHardwareVsync();
1306 } else {
1307 disableHardwareVsync(false);
1308 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001309}
1310
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001311void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001312 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1313 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001314}
1315
Lloyd Pique715a2c12017-12-14 17:18:08 -08001316void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1317 HWC2::Connection connection) {
1318 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1319 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001320
Lloyd Piqueba04e622017-12-14 17:11:26 -08001321 // Ignore events that do not have the right sequenceId.
1322 if (sequenceId != getBE().mComposerSequenceId) {
1323 return;
1324 }
1325
Steven Thomasb02664d2017-07-26 18:48:28 -07001326 // Only lock if we're not on the main thread. This function is normally
1327 // called on a hwbinder thread, but for the primary display it's called on
1328 // the main thread with the state lock already held, so don't attempt to
1329 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001330 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001331
Lloyd Pique715a2c12017-12-14 17:18:08 -08001332 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001333
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001334 if (std::this_thread::get_id() == mMainThreadId) {
1335 // Process all pending hot plug events immediately if we are on the main thread.
1336 processDisplayHotplugEventsLocked();
1337 }
1338
Lloyd Piqueba04e622017-12-14 17:11:26 -08001339 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001340}
1341
Steven Thomasb02664d2017-07-26 18:48:28 -07001342void SurfaceFlinger::onRefreshReceived(int sequenceId,
1343 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001344 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001345 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001347 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001348 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001349}
1350
Dan Stoza9e56aa02015-11-02 13:00:03 -08001351void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001352 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001353 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001354 getHwComposer().setVsyncEnabled(disp,
1355 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001356}
1357
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001358// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001359void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001360 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001361 // Clear the drawing state so that the logic inside of
1362 // handleTransactionLocked will fire. It will determine the delta between
1363 // mCurrentState and mDrawingState and re-apply all changes when we make the
1364 // transition.
1365 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001366 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001367 mDisplays.clear();
1368}
1369
Steven Thomas050b2c82017-03-06 11:45:16 -08001370void SurfaceFlinger::updateVrFlinger() {
1371 if (!mVrFlinger)
1372 return;
1373 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001374 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001375 return;
1376 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001377
David Sodman105b7dc2017-11-04 20:28:14 -07001378 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 ALOGE("Vr flinger is only supported for remote hardware composer"
1380 " service connections. Ignoring request to transition to vr"
1381 " flinger.");
1382 mVrFlingerRequestsDisplay = false;
1383 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001384 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001385
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001386 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001388 int currentDisplayPowerMode = getDefaultDisplayDeviceLocked()->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001389
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001391 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001392 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001393
Steven Thomasb02664d2017-07-26 18:48:28 -07001394 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001395 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001396 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1397 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001398 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001399
David Sodman105b7dc2017-11-04 20:28:14 -07001400 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1401 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001402
1403 if (vrFlingerRequestsDisplay) {
1404 mVrFlinger->GrantDisplayOwnership();
1405 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001406 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001408
1409 mVisibleRegionsDirty = true;
1410 invalidateHwcGeometry();
1411
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001412 // Re-enable default display.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001413 setPowerModeInternal(getDefaultDisplayDeviceLocked(), currentDisplayPowerMode,
1414 /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001415
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001417 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 const nsecs_t period = activeConfig->getVsyncPeriod();
1419 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001420
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 // Use phase of 0 since phase is not known.
1422 // Use latency of 0, which will snap to the ideal latency.
1423 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001424
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001425 android_atomic_or(1, &mRepaintEverything);
1426 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001427}
1428
Mathias Agopian4fec8732012-06-29 14:12:52 -07001429void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001430 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001431 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001432 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001433 bool frameMissed = !mHadClientComposition &&
1434 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001435 (mPreviousPresentFence->getSignalTime() ==
1436 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001437 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001438 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001439 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001440 mTimeStats.incrementMissedFrames();
1441 if (mPropagateBackpressure) {
1442 signalLayerUpdate();
1443 break;
1444 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001445 }
Dan Stoza50182882016-07-08 12:02:20 -07001446
Steven Thomas050b2c82017-03-06 11:45:16 -08001447 // Now that we're going to make it to the handleMessageTransaction()
1448 // call below it's safe to call updateVrFlinger(), which will
1449 // potentially trigger a display handoff.
1450 updateVrFlinger();
1451
Dan Stoza6b9454d2014-11-07 16:00:59 -08001452 bool refreshNeeded = handleMessageTransaction();
1453 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001454 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001455 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001456 // Signal a refresh if a transaction modified the window state,
1457 // a new buffer was latched, or if HWC has requested a full
1458 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001459 signalRefresh();
1460 }
1461 break;
1462 }
1463 case MessageQueue::REFRESH: {
1464 handleMessageRefresh();
1465 break;
1466 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001467 }
1468}
1469
Dan Stoza6b9454d2014-11-07 16:00:59 -08001470bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001471 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001472 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001473 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001474 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001475 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001476 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001477}
1478
Dan Stoza6b9454d2014-11-07 16:00:59 -08001479bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001480 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001481 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001482}
1483
1484void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001485 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001486
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001487 mRefreshPending = false;
1488
Chia-I Wu30505fb2018-03-26 16:20:31 -07001489 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001490
Chia-I Wu30505fb2018-03-26 16:20:31 -07001491 preComposition(refreshStartTime);
1492 rebuildLayerStacks();
1493 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001494 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001495 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001496 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001497 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001498 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001499
David Sodman105b7dc2017-11-04 20:28:14 -07001500 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001501
1502 mHadClientComposition = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001503 for (size_t i = 0; i < mDisplays.size(); ++i) {
1504 const auto& display = mDisplays[i];
Dan Stozabfbffeb2016-07-21 14:49:33 -07001505 mHadClientComposition = mHadClientComposition ||
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001506 getBE().mHwc->hasClientComposition(display->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001507 }
Dan Stoza84d619e2018-03-28 17:07:36 -07001508 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001509
Dan Stoza9e56aa02015-11-02 13:00:03 -08001510 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001511}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001512
Mathias Agopiancd60f992012-08-16 16:28:27 -07001513void SurfaceFlinger::doDebugFlashRegions()
1514{
1515 // is debugging enabled
1516 if (CC_LIKELY(!mDebugRegion))
1517 return;
1518
1519 const bool repaintEverything = mRepaintEverything;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001520 for (size_t i = 0; i < mDisplays.size(); ++i) {
1521 const auto& display = mDisplays[i];
1522 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001523 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001524 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001525 if (!dirtyRegion.isEmpty()) {
1526 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001527 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001528
1529 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001530 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001531 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001532 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1533
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001534 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001535 }
1536 }
1537 }
1538
1539 postFramebuffer();
1540
1541 if (mDebugRegion > 1) {
1542 usleep(mDebugRegion * 1000);
1543 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001544
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001545 for (size_t i = 0; i < mDisplays.size(); ++i) {
1546 const auto& display = mDisplays[i];
1547 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001548 continue;
1549 }
1550
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001551 status_t result = display->prepareFrame(*getBE().mHwc);
1552 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
1553 display->getHwcDisplayId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001554 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555}
1556
Adrian Roos1e1a1282017-11-01 19:05:31 +01001557void SurfaceFlinger::doTracing(const char* where) {
1558 ATRACE_CALL();
1559 ATRACE_NAME(where);
1560 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001561 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001562 }
1563}
1564
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001565void SurfaceFlinger::logLayerStats() {
1566 ATRACE_CALL();
1567 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001568 for (size_t i = 0; i < mDisplays.size(); ++i) {
1569 const auto& display = mDisplays[i];
1570 if (display->isPrimary()) {
1571 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001572 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001573 }
1574 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001575
1576 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001577 }
1578}
1579
Chia-I Wu30505fb2018-03-26 16:20:31 -07001580void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001582 ATRACE_CALL();
1583 ALOGV("preComposition");
1584
Mathias Agopiancd60f992012-08-16 16:28:27 -07001585 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001586 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001587 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588 needExtraInvalidate = true;
1589 }
Robert Carr2047fae2016-11-28 14:09:09 -08001590 });
1591
Mathias Agopiancd60f992012-08-16 16:28:27 -07001592 if (needExtraInvalidate) {
1593 signalLayerUpdate();
1594 }
1595}
1596
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001597void SurfaceFlinger::updateCompositorTiming(
1598 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1599 std::shared_ptr<FenceTime>& presentFenceTime) {
1600 // Update queue of past composite+present times and determine the
1601 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001602 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001603 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001604 while (!getBE().mCompositePresentTimes.empty()) {
1605 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001606 // Cached values should have been updated before calling this method,
1607 // which helps avoid duplicate syscalls.
1608 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1609 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1610 break;
1611 }
1612 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001613 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001614 }
1615
1616 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001617 while (getBE().mCompositePresentTimes.size() > 16) {
1618 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001619 }
1620
Brian Andersond0010582017-03-07 13:20:31 -08001621 setCompositorTimingSnapped(
1622 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1623}
1624
1625void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1626 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001627 // Integer division and modulo round toward 0 not -inf, so we need to
1628 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001629 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001630 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1631 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1632
Brian Andersond0010582017-03-07 13:20:31 -08001633 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1634 if (idealLatency <= 0) {
1635 idealLatency = vsyncInterval;
1636 }
1637
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001638 // Snap the latency to a value that removes scheduling jitter from the
1639 // composition and present times, which often have >1ms of jitter.
1640 // Reducing jitter is important if an app attempts to extrapolate
1641 // something (such as user input) to an accurate diasplay time.
1642 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1643 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001644 nsecs_t bias = vsyncInterval / 2;
1645 int64_t extraVsyncs =
1646 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1647 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1648 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001649
David Sodman99974d22017-11-28 12:04:33 -08001650 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1651 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1652 getBE().mCompositorTiming.interval = vsyncInterval;
1653 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001654}
1655
Chia-I Wu30505fb2018-03-26 16:20:31 -07001656void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001657{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001658 ATRACE_CALL();
1659 ALOGV("postComposition");
1660
Brian Anderson3546a3f2016-07-14 11:51:14 -07001661 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001662 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001663 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001664 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001665 }
1666
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001667 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001668 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001669
David Sodman73beded2017-11-15 11:56:06 -08001670 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001671 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001672 if (display && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001673 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001674 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001675 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001676 } else {
1677 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1678 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001679
David Sodman73beded2017-11-15 11:56:06 -08001680 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001681 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001682 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001683 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001684
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001685 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1686 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1687
Chia-I Wu30505fb2018-03-26 16:20:31 -07001688 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001689 // when we started doing work for this frame, but that should be okay
1690 // since updateCompositorTiming has snapping logic.
1691 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001692 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001693 CompositorTiming compositorTiming;
1694 {
David Sodman99974d22017-11-28 12:04:33 -08001695 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1696 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001697 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001698
Robert Carr2047fae2016-11-28 14:09:09 -08001699 mDrawingState.traverseInZOrder([&](Layer* layer) {
1700 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001701 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001702 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001703 recordBufferingStats(layer->getName().string(),
1704 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001705 }
Robert Carr2047fae2016-11-28 14:09:09 -08001706 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001707
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001708 if (presentFenceTime->isValid()) {
1709 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001710 enableHardwareVsync();
1711 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001712 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001713 }
1714 }
1715
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001716 if (!hasSyncFramework) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001717 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001718 enableHardwareVsync();
1719 }
1720 }
1721
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001722 if (mAnimCompositionPending) {
1723 mAnimCompositionPending = false;
1724
Brian Anderson4e606e32017-03-16 15:34:57 -07001725 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001726 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001727 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001728 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001729 // The HWC doesn't support present fences, so use the refresh
1730 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001731 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001732 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001733 mAnimFrameTracker.setActualPresentTime(presentTime);
1734 }
1735 mAnimFrameTracker.advanceFrame();
1736 }
Dan Stozab90cf072015-03-05 11:05:59 -08001737
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001738 mTimeStats.incrementTotalFrames();
1739 if (mHadClientComposition) {
1740 mTimeStats.incrementClientCompositionFrames();
1741 }
1742
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001743 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001744 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001745 return;
1746 }
1747
1748 nsecs_t currentTime = systemTime();
1749 if (mHasPoweredOff) {
1750 mHasPoweredOff = false;
1751 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001752 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001753 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001754 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1755 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001756 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001757 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001758 }
David Sodman4a36e932017-11-07 14:29:47 -08001759 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001760 }
David Sodman4a36e932017-11-07 14:29:47 -08001761 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001762}
1763
1764void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001765 ATRACE_CALL();
1766 ALOGV("rebuildLayerStacks");
1767
Mathias Agopiancd60f992012-08-16 16:28:27 -07001768 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001769 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001770 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001771 mVisibleRegionsDirty = false;
1772 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001773
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001774 for (size_t i = 0; i < mDisplays.size(); ++i) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001775 Region opaqueRegion;
1776 Region dirtyRegion;
1777 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001778 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001779 const auto& display = mDisplays[i];
1780 const Transform& tr = display->getTransform();
1781 const Rect bounds = display->getBounds();
1782 if (display->isPoweredOn()) {
1783 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001784
Jeff Sharkey76488112017-02-27 14:15:18 -07001785 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001786 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001787 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001788 Region drawRegion(tr.transform(
1789 layer->visibleNonTransparentRegion));
1790 drawRegion.andSelf(bounds);
1791 if (!drawRegion.isEmpty()) {
1792 layersSortedByZ.add(layer);
1793 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001794 // Clear out the HWC layer if this layer was
1795 // previously visible, but no longer is
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001796 hwcLayerDestroyed = layer->destroyHwcLayer(display->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001797 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001798 } else {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001799 // WM changes display->layerStack upon sleep/awake.
Chia-I Wu30505fb2018-03-26 16:20:31 -07001800 // Here we make sure we delete the HWC layers even if
1801 // WM changed their layer stack.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001802 hwcLayerDestroyed = layer->destroyHwcLayer(display->getHwcDisplayId());
Chia-I Wu83806892017-11-16 10:50:20 -08001803 }
1804
1805 // If a layer is not going to get a release fence because
1806 // it is invisible, but it is also going to release its
1807 // old buffer, add it to the list of layers needing
1808 // fences.
1809 if (hwcLayerDestroyed) {
1810 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1811 mLayersWithQueuedFrames.cend(), layer);
1812 if (found != mLayersWithQueuedFrames.cend()) {
1813 layersNeedingFences.add(layer);
1814 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001815 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001816 });
1817 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001818 display->setVisibleLayersSortedByZ(layersSortedByZ);
1819 display->setLayersNeedingFences(layersNeedingFences);
1820 display->undefinedRegion.set(bounds);
1821 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1822 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001823 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001824 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001825}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001826
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001827// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001828// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001829// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001830// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001831// The returned HDR data space is one of
1832// - Dataspace::UNKNOWN
1833// - Dataspace::BT2020_HLG
1834// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001835Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1836 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001837 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001838 *outHdrDataSpace = Dataspace::UNKNOWN;
1839
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001840 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001841 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001842 case Dataspace::V0_SCRGB:
1843 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001844 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001845 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001846 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001847 case Dataspace::BT2020_PQ:
1848 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001849 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001850 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001851 case Dataspace::BT2020_HLG:
1852 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001853 // When there's mixed PQ content and HLG content, we set the HDR
1854 // data space to be BT2020_PQ and convert HLG to PQ.
1855 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1856 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001857 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001858 break;
1859 default:
1860 break;
1861 }
Romain Guy54f154a2017-10-24 21:40:32 +01001862 }
1863
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001864 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001865}
1866
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001867// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001868void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1869 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001870 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1871 *outMode = ColorMode::NATIVE;
1872 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001873 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001874 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001875 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001876
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001877 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001878 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001879
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001880 // respect hdrDataSpace only when there is modern HDR support
1881 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001882 display->hasModernHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001883 if (isHdr) {
1884 bestDataSpace = hdrDataSpace;
1885 }
1886
Chia-I Wu0d711262018-05-21 15:19:35 -07001887 RenderIntent intent;
1888 switch (mDisplayColorSetting) {
1889 case DisplayColorSetting::MANAGED:
1890 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001891 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001892 break;
1893 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001894 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001895 break;
1896 default: // vendor display color setting
1897 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1898 break;
1899 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001900
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001901 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001902}
1903
Chia-I Wu30505fb2018-03-26 16:20:31 -07001904void SurfaceFlinger::setUpHWComposer() {
1905 ATRACE_CALL();
1906 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001907
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001908 for (size_t i = 0; i < mDisplays.size(); ++i) {
1909 const auto& display = mDisplays[i];
1910 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
1911 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1912 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07001913
1914 // If nothing has changed (!dirty), don't recompose.
1915 // If something changed, but we don't currently have any visible layers,
1916 // and didn't when we last did a composition, then skip it this time.
1917 // The second rule does two things:
1918 // - When all layers are removed from a display, we'll emit one black
1919 // frame, then nothing more until we get new layers.
1920 // - When a display is created with a private layer stack, we won't
1921 // emit any black frames until a layer is added to the layer stack.
1922 bool mustRecompose = dirty && !(empty && wasEmpty);
1923
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001924 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
1925 display->getHwcDisplayId(), mustRecompose ? "doing" : "skipping",
1926 dirty ? "+" : "-", empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07001927
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001928 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001929
1930 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001931 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07001932 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001933 }
1934
Chia-I Wu30505fb2018-03-26 16:20:31 -07001935 // build the h/w work list
1936 if (CC_UNLIKELY(mGeometryInvalid)) {
1937 mGeometryInvalid = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001938 for (size_t i = 0; i < mDisplays.size(); ++i) {
1939 const auto& display = mDisplays[i];
1940 const auto hwcId = display->getHwcDisplayId();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001941 if (hwcId >= 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001942 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001943 for (size_t i = 0; i < currentLayers.size(); i++) {
1944 const auto& layer = currentLayers[i];
1945 if (!layer->hasHwcLayer(hwcId)) {
1946 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
1947 layer->forceClientComposition(hwcId);
1948 continue;
1949 }
1950 }
1951
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001952 layer->setGeometry(display, i);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001953 if (mDebugDisableHWC || mDebugRegion) {
1954 layer->forceClientComposition(hwcId);
1955 }
1956 }
1957 }
1958 }
1959 }
1960
Chia-I Wu30505fb2018-03-26 16:20:31 -07001961 // Set the per-frame data
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001962 for (size_t i = 0; i < mDisplays.size(); ++i) {
1963 const auto& display = mDisplays[i];
1964 const auto hwcId = display->getHwcDisplayId();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001965
1966 if (hwcId < 0) {
1967 continue;
1968 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07001969 if (mDrawingState.colorMatrixChanged) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001970 display->setColorTransform(mDrawingState.colorMatrix);
Chia-I Wu28f320b2018-05-03 11:02:56 -07001971 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001972 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
1973 display->getHwcDisplayId(), result);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001974 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001975 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001976 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1977 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001978 !display->hasHDR10Support()) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001979 layer->forceClientComposition(hwcId);
1980 }
Chia-I Wu01591c92018-05-22 12:03:00 -07001981 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1982 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001983 !display->hasHLGSupport()) {
Peiyong Linf59a7192018-04-25 11:19:31 -07001984 layer->forceClientComposition(hwcId);
1985 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001986
1987 if (layer->getForceClientComposition(hwcId)) {
1988 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1989 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1990 continue;
1991 }
1992
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001993 layer->setPerFrameData(display);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001994 }
1995
1996 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001997 ColorMode colorMode;
1998 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001999 RenderIntent renderIntent;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002000 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
2001 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002002 }
2003 }
2004
Chia-I Wu28f320b2018-05-03 11:02:56 -07002005 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07002006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002007 for (size_t i = 0; i < mDisplays.size(); ++i) {
2008 const auto& display = mDisplays[i];
2009 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002010 continue;
2011 }
2012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002013 status_t result = display->prepareFrame(*getBE().mHwc);
2014 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
2015 display->getHwcDisplayId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002016 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002017}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002018
Mathias Agopiancd60f992012-08-16 16:28:27 -07002019void SurfaceFlinger::doComposition() {
2020 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002021 ALOGV("doComposition");
2022
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002023 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002024 for (size_t i = 0; i < mDisplays.size(); ++i) {
2025 const auto& display = mDisplays[i];
2026 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002027 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002028 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002029
2030 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002031 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002032
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002033 display->dirtyRegion.clear();
2034 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002035 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002036 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002037 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002038}
2039
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002040void SurfaceFlinger::postFramebuffer()
2041{
Mathias Agopian841cde52012-03-01 15:44:37 -08002042 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002043 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002044
Mathias Agopiana44b0412011-10-16 18:46:35 -07002045 const nsecs_t now = systemTime();
2046 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002047
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002048 for (size_t i = 0; i < mDisplays.size(); ++i) {
2049 const auto& display = mDisplays[i];
2050 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002051 continue;
2052 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002053 const auto hwcId = display->getHwcDisplayId();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002054 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002055 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002056 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002057 display->onSwapBuffersCompleted();
2058 display->makeCurrent();
2059 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002060 // The layer buffer from the previous frame (if any) is released
2061 // by HWC only when the release fence from this frame (if any) is
2062 // signaled. Always get the release fence from HWC first.
2063 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002064 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002065
2066 // If the layer was client composited in the previous frame, we
2067 // need to merge with the previous client target acquire fence.
2068 // Since we do not track that, always merge with the current
2069 // client target acquire fence when it is available, even though
2070 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002071 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002072 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002073 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002074 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002075
David Sodmanb8af7922017-12-21 15:17:55 -08002076 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002077 }
Chia-I Wu83806892017-11-16 10:50:20 -08002078
2079 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002080 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002081 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002082 if (!display->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002083 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002084 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002085 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002086 }
2087 }
2088
Dan Stoza9e56aa02015-11-02 13:00:03 -08002089 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002090 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002091 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002092 }
2093
Mathias Agopiana44b0412011-10-16 18:46:35 -07002094 mLastSwapBufferTime = systemTime() - now;
2095 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002096
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002097 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002098 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2099 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2100 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2101 logFrameStats();
2102 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002103 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002104}
2105
Mathias Agopian87baae12012-07-31 12:38:26 -07002106void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002107{
Mathias Agopian841cde52012-03-01 15:44:37 -08002108 ATRACE_CALL();
2109
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002110 // here we keep a copy of the drawing state (that is the state that's
2111 // going to be overwritten by handleTransactionLocked()) outside of
2112 // mStateLock so that the side-effects of the State assignment
2113 // don't happen with mStateLock held (which can cause deadlocks).
2114 State drawingState(mDrawingState);
2115
Mathias Agopianca4d3602011-05-19 15:38:14 -07002116 Mutex::Autolock _l(mStateLock);
2117 const nsecs_t now = systemTime();
2118 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002119
Mathias Agopianca4d3602011-05-19 15:38:14 -07002120 // Here we're guaranteed that some transaction flags are set
2121 // so we can call handleTransactionLocked() unconditionally.
2122 // We call getTransactionFlags(), which will also clear the flags,
2123 // with mStateLock held to guarantee that mCurrentState won't change
2124 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002125
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002126 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002127 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002128 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002129
Mathias Agopianca4d3602011-05-19 15:38:14 -07002130 mLastTransactionTime = systemTime() - now;
2131 mDebugInTransaction = 0;
2132 invalidateHwcGeometry();
2133 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002134}
2135
Lloyd Pique715a2c12017-12-14 17:18:08 -08002136DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002137 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002138 // Figure out whether the event is for the primary display or an
2139 // external display by matching the Hwc display id against one for a
2140 // connected display. If we did not find a match, we then check what
2141 // displays are not already connected to determine the type. If we don't
2142 // have a connected primary display, we assume the new display is meant to
2143 // be the primary display, and then if we don't have an external display,
2144 // we assume it is that.
2145 const auto primaryDisplayId =
2146 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2147 const auto externalDisplayId =
2148 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2149 if (primaryDisplayId && primaryDisplayId == display) {
2150 return DisplayDevice::DISPLAY_PRIMARY;
2151 } else if (externalDisplayId && externalDisplayId == display) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002152 return DisplayDevice::DISPLAY_EXTERNAL;
Lloyd Pique715a2c12017-12-14 17:18:08 -08002153 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2154 return DisplayDevice::DISPLAY_PRIMARY;
2155 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2156 return DisplayDevice::DISPLAY_EXTERNAL;
2157 }
2158
2159 return DisplayDevice::DISPLAY_ID_INVALID;
2160}
2161
Lloyd Piqueba04e622017-12-14 17:11:26 -08002162void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2163 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002164 auto displayType = determineDisplayType(event.display, event.connection);
2165 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2166 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2167 continue;
2168 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002169
2170 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2171 ALOGE("External displays are not supported by the vr hardware composer.");
2172 continue;
2173 }
2174
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002175 const auto displayId =
2176 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
2177 if (displayId) {
2178 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.display, *displayId);
2179 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002180
2181 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002182 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002183 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002184 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002185 DisplayDeviceState info;
2186 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002187 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2188 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002189 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002190 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002191 mInterceptor->saveDisplayCreation(info);
2192 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002193 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002194 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002195
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002196 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002197 if (idx >= 0) {
2198 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002199 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002200 mCurrentState.displays.removeItemsAt(idx);
2201 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002202 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002203 }
2204
2205 processDisplayChangesLocked();
2206 }
2207
2208 mPendingHotplugEvents.clear();
2209}
2210
Lloyd Pique99d3da52018-01-22 17:48:03 -08002211sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002212 const wp<IBinder>& displayToken, int hwcId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002213 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002214 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002215 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002216
Lloyd Pique99d3da52018-01-22 17:48:03 -08002217 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002218 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002219 for (ColorMode colorMode : modes) {
2220 switch (colorMode) {
2221 case ColorMode::DISPLAY_P3:
2222 case ColorMode::ADOBE_RGB:
2223 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002224 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002225 break;
2226 default:
2227 break;
2228 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002229
2230 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2231 colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002232 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002233 }
2234 }
2235
Peiyong Lin62665892018-04-16 11:07:44 -07002236 HdrCapabilities hdrCapabilities;
2237 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002238
2239 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2240 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2241
2242 /*
2243 * Create our display's surface
2244 */
2245 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2246 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002247 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002248 renderSurface->setNativeWindow(nativeWindow.get());
2249 const int displayWidth = renderSurface->queryWidth();
2250 const int displayHeight = renderSurface->queryHeight();
2251
2252 // Make sure that composition can never be stalled by a virtual display
2253 // consumer that isn't processing buffers fast enough. We have to do this
2254 // in two places:
2255 // * Here, in case the display is composed entirely by HWC.
2256 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2257 // window's swap interval in eglMakeCurrent, so they'll override the
2258 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002259 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002260 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2261 }
2262
2263 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002264 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002265
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002266 sp<DisplayDevice> display =
2267 new DisplayDevice(this, state.type, hwcId, state.isSecure, displayToken, nativeWindow,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002268 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin0ac5f4e2018-04-19 22:06:34 -07002269 hasWideColorGamut, hdrCapabilities,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002270 getHwComposer().getSupportedPerFrameMetadata(hwcId), hwcColorModes,
2271 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002272
2273 if (maxFrameBufferAcquiredBuffers >= 3) {
2274 nativeWindowSurface->preallocateBuffers();
2275 }
2276
2277 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002278 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2279 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002280 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002281 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002282 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002283 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002284 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002285 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002286 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002287 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002288 display->setLayerStack(state.layerStack);
2289 display->setProjection(state.orientation, state.viewport, state.frame);
2290 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002291
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002292 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002293}
2294
Lloyd Pique347200f2017-12-14 17:00:15 -08002295void SurfaceFlinger::processDisplayChangesLocked() {
2296 // here we take advantage of Vector's copy-on-write semantics to
2297 // improve performance by skipping the transaction entirely when
2298 // know that the lists are identical
2299 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2300 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2301 if (!curr.isIdenticalTo(draw)) {
2302 mVisibleRegionsDirty = true;
2303 const size_t cc = curr.size();
2304 size_t dc = draw.size();
2305
2306 // find the displays that were removed
2307 // (ie: in drawing state but not in current state)
2308 // also handle displays that changed
2309 // (ie: displays that are in both lists)
2310 for (size_t i = 0; i < dc;) {
2311 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2312 if (j < 0) {
2313 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002314 // Call makeCurrent() on the primary display so we can
2315 // be sure that nothing associated with this display
2316 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002317 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2318 defaultDisplay->makeCurrent();
2319 }
2320 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2321 display->disconnect(getHwComposer());
2322 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002323 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2324 mEventThread->onHotplugReceived(draw[i].type, false);
2325 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002326 } else {
2327 // this display is in both lists. see if something changed.
2328 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002329 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002330 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2331 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2332 if (state_binder != draw_binder) {
2333 // changing the surface is like destroying and
2334 // recreating the DisplayDevice, so we just remove it
2335 // from the drawing state, so that it get re-added
2336 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002337 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2338 display->disconnect(getHwComposer());
2339 }
2340 mDisplays.removeItem(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002341 mDrawingState.displays.removeItemsAt(i);
2342 dc--;
2343 // at this point we must loop to the next item
2344 continue;
2345 }
2346
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002347 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002348 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002349 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002350 }
2351 if ((state.orientation != draw[i].orientation) ||
2352 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002353 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002354 }
2355 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002356 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002357 }
2358 }
2359 }
2360 ++i;
2361 }
2362
2363 // find displays that were added
2364 // (ie: in current state but not in drawing state)
2365 for (size_t i = 0; i < cc; i++) {
2366 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2367 const DisplayDeviceState& state(curr[i]);
2368
2369 sp<DisplaySurface> dispSurface;
2370 sp<IGraphicBufferProducer> producer;
2371 sp<IGraphicBufferProducer> bqProducer;
2372 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002373 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002374
2375 int32_t hwcId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002376 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002377 // Virtual displays without a surface are dormant:
2378 // they have external state (layer stack, projection,
2379 // etc.) but no internal state (i.e. a DisplayDevice).
2380 if (state.surface != nullptr) {
2381 // Allow VR composer to use virtual displays.
2382 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2383 int width = 0;
2384 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2385 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2386 int height = 0;
2387 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2388 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2389 int intFormat = 0;
2390 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2391 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002392 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002393
2394 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2395 }
2396
2397 // TODO: Plumb requested format back up to consumer
2398
2399 sp<VirtualDisplaySurface> vds =
2400 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2401 bqProducer, bqConsumer,
2402 state.displayName);
2403
2404 dispSurface = vds;
2405 producer = vds;
2406 }
2407 } else {
2408 ALOGE_IF(state.surface != nullptr,
2409 "adding a supported display, but rendering "
2410 "surface is provided (%p), ignoring it",
2411 state.surface.get());
2412
2413 hwcId = state.type;
2414 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2415 producer = bqProducer;
2416 }
2417
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002418 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002419 if (dispSurface != nullptr) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002420 mDisplays.add(displayToken,
2421 setupNewDisplayDeviceInternal(displayToken, hwcId, state,
2422 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002423 if (!state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002424 mEventThread->onHotplugReceived(state.type, true);
2425 }
2426 }
2427 }
2428 }
2429 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002430
2431 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002432}
2433
Mathias Agopian87baae12012-07-31 12:38:26 -07002434void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002435{
Dan Stoza7dde5992015-05-22 09:51:44 -07002436 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002437 mCurrentState.traverseInZOrder([](Layer* layer) {
2438 layer->notifyAvailableFrames();
2439 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002440
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002441 /*
2442 * Traversal of the children
2443 * (perform the transaction for each of them if needed)
2444 */
2445
Mathias Agopian3559b072012-08-15 13:46:03 -07002446 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002447 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002448 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002449 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450
2451 const uint32_t flags = layer->doTransaction(0);
2452 if (flags & Layer::eVisibleRegion)
2453 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002454 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455 }
2456
2457 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002458 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002459 */
2460
Mathias Agopiane57f2922012-08-09 16:29:12 -07002461 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002462 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002463 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002464 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002466 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002467 // The transform hint might have changed for some layers
2468 // (either because a display has changed, or because a layer
2469 // as changed).
2470 //
2471 // Walk through all the layers in currentLayers,
2472 // and update their transform hint.
2473 //
2474 // If a layer is visible only on a single display, then that
2475 // display is used to calculate the hint, otherwise we use the
2476 // default display.
2477 //
2478 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2479 // the hint is set before we acquire a buffer from the surface texture.
2480 //
2481 // NOTE: layer transactions have taken place already, so we use their
2482 // drawing state. However, SurfaceFlinger's own transaction has not
2483 // happened yet, so we must use the current state layer list
2484 // (soon to become the drawing state list).
2485 //
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002486 sp<const DisplayDevice> display;
Mathias Agopian84300952012-11-21 16:02:13 -08002487 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002488 bool first = true;
2489 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002490 // NOTE: we rely on the fact that layers are sorted by
2491 // layerStack first (so we don't have to traverse the list
2492 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002493 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002494 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002495 currentlayerStack = layerStack;
2496 // figure out if this layerstack is mirrored
2497 // (more than one display) if so, pick the default display,
2498 // if not, pick the only display it's on.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002499 display = nullptr;
2500 for (size_t i = 0; i < mDisplays.size(); ++i) {
2501 if (layer->belongsToDisplay(mDisplays[i]->getLayerStack(),
2502 mDisplays[i]->isPrimary())) {
2503 if (display) {
2504 display = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002505 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002506 } else {
2507 display = mDisplays[i];
Mathias Agopian84300952012-11-21 16:02:13 -08002508 }
2509 }
2510 }
2511 }
Chet Haase91d25932013-04-11 15:24:55 -07002512
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002513 if (!display) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002514 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2515 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002516
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002517 // could be null when this layer is using a layerStack
2518 // that is not visible on any display. Also can occur at
2519 // screen off/on times.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002520 display = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002521 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002522
2523 // disp can be null if there is no display available at all to get
2524 // the transform hint from.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002525 if (display) {
2526 layer->updateTransformHint(display);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002527 }
Robert Carr2047fae2016-11-28 14:09:09 -08002528
2529 first = false;
2530 });
Mathias Agopian84300952012-11-21 16:02:13 -08002531 }
2532
2533
Mathias Agopian3559b072012-08-15 13:46:03 -07002534 /*
2535 * Perform our own transaction if needed
2536 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002537
2538 if (mLayersAdded) {
2539 mLayersAdded = false;
2540 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002541 mVisibleRegionsDirty = true;
2542 }
2543
2544 // some layers might have been removed, so
2545 // we need to update the regions they're exposing.
2546 if (mLayersRemoved) {
2547 mLayersRemoved = false;
2548 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002549 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002550 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002551 // this layer is not visible anymore
2552 // TODO: we could traverse the tree from front to back and
2553 // compute the actual visible region
2554 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002555 Region visibleReg;
2556 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002557 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002558 }
Robert Carr2047fae2016-11-28 14:09:09 -08002559 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002560 }
2561
2562 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002563
2564 updateCursorAsync();
2565}
2566
2567void SurfaceFlinger::updateCursorAsync()
2568{
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002569 for (size_t i = 0; i < mDisplays.size(); ++i) {
2570 const auto& display = mDisplays[i];
2571 if (display->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002572 continue;
2573 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002574
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002575 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2576 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002577 }
2578 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002579}
2580
2581void SurfaceFlinger::commitTransaction()
2582{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002583 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002584 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002585 for (const auto& l : mLayersPendingRemoval) {
2586 recordBufferingStats(l->getName().string(),
2587 l->getOccupancyHistory(true));
2588 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002589 }
2590 mLayersPendingRemoval.clear();
2591 }
2592
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002593 // If this transaction is part of a window animation then the next frame
2594 // we composite should be considered an animation as well.
2595 mAnimCompositionPending = mAnimTransactionPending;
2596
Mathias Agopian4fec8732012-06-29 14:12:52 -07002597 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002598 // clear the "changed" flags in current state
2599 mCurrentState.colorMatrixChanged = false;
2600
Robert Carr1f0a16a2016-10-24 16:27:39 -07002601 mDrawingState.traverseInZOrder([](Layer* layer) {
2602 layer->commitChildList();
2603 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002604 mTransactionPending = false;
2605 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002606 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607}
2608
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002609void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2610 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002611 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002612 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002613
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002614 Region aboveOpaqueLayers;
2615 Region aboveCoveredLayers;
2616 Region dirty;
2617
Mathias Agopian87baae12012-07-31 12:38:26 -07002618 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002619
Robert Carr2047fae2016-11-28 14:09:09 -08002620 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002622 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002623
Jesse Hall01e29052013-02-19 16:13:35 -08002624 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002625 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002626 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002627 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002628
Mathias Agopianab028732010-03-16 16:41:46 -07002629 /*
2630 * opaqueRegion: area of a surface that is fully opaque.
2631 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002633
2634 /*
2635 * visibleRegion: area of a surface that is visible on screen
2636 * and not fully transparent. This is essentially the layer's
2637 * footprint minus the opaque regions above it.
2638 * Areas covered by a translucent surface are considered visible.
2639 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002641
2642 /*
2643 * coveredRegion: area of a surface that is covered by all
2644 * visible regions above it (which includes the translucent areas).
2645 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002647
Jesse Halla8026d22012-09-25 13:25:04 -07002648 /*
2649 * transparentRegion: area of a surface that is hinted to be completely
2650 * transparent. This is only used to tell when the layer has no visible
2651 * non-transparent regions and can be removed from the layer list. It
2652 * does not affect the visibleRegion of this layer or any layers
2653 * beneath it. The hint may not be correct if apps don't respect the
2654 * SurfaceView restrictions (which, sadly, some don't).
2655 */
2656 Region transparentRegion;
2657
Mathias Agopianab028732010-03-16 16:41:46 -07002658
2659 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002660 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002661 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002662 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002664 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002665 if (!visibleRegion.isEmpty()) {
2666 // Remove the transparent area from the visible region
2667 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002668 if (tr.preserveRects()) {
2669 // transform the transparent region
2670 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002671 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002672 // transformation too complex, can't do the
2673 // transparent region optimization.
2674 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002675 }
Mathias Agopianab028732010-03-16 16:41:46 -07002676 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002677
Mathias Agopianab028732010-03-16 16:41:46 -07002678 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002679 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002680 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002681 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2682 // the opaque region is the layer's footprint
2683 opaqueRegion = visibleRegion;
2684 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002685 }
2686 }
2687
Robert Carre5f4f692018-01-12 13:12:28 -08002688 if (visibleRegion.isEmpty()) {
2689 layer->clearVisibilityRegions();
2690 return;
2691 }
2692
Mathias Agopianab028732010-03-16 16:41:46 -07002693 // Clip the covered region to the visible region
2694 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2695
2696 // Update aboveCoveredLayers for next (lower) layer
2697 aboveCoveredLayers.orSelf(visibleRegion);
2698
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 // subtract the opaque region covered by the layers above us
2700 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002701
2702 // compute this layer's dirty region
2703 if (layer->contentDirty) {
2704 // we need to invalidate the whole region
2705 dirty = visibleRegion;
2706 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002707 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708 layer->contentDirty = false;
2709 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002710 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002711 * the exposed region consists of two components:
2712 * 1) what's VISIBLE now and was COVERED before
2713 * 2) what's EXPOSED now less what was EXPOSED before
2714 *
2715 * note that (1) is conservative, we start with the whole
2716 * visible region but only keep what used to be covered by
2717 * something -- which mean it may have been exposed.
2718 *
2719 * (2) handles areas that were not covered by anything but got
2720 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002721 */
Mathias Agopianab028732010-03-16 16:41:46 -07002722 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002723 const Region oldVisibleRegion = layer->visibleRegion;
2724 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002725 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2726 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002727 }
2728 dirty.subtractSelf(aboveOpaqueLayers);
2729
2730 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002731 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002732
Mathias Agopianab028732010-03-16 16:41:46 -07002733 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002734 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002735
Jesse Halla8026d22012-09-25 13:25:04 -07002736 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737 layer->setVisibleRegion(visibleRegion);
2738 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002739 layer->setVisibleNonTransparentRegion(
2740 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002741 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742
Mathias Agopian87baae12012-07-31 12:38:26 -07002743 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744}
2745
Chia-I Wuab0c3192017-08-01 11:29:00 -07002746void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002747 for (size_t i = 0; i < mDisplays.size(); ++i) {
2748 const auto& display = mDisplays[i];
2749 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2750 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002751 }
2752 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002753}
2754
Dan Stoza6b9454d2014-11-07 16:00:59 -08002755bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002757 ALOGV("handlePageFlip");
2758
Brian Andersond6927fb2016-07-23 23:37:30 -07002759 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760
Mathias Agopian4fec8732012-06-29 14:12:52 -07002761 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002762 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002763 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002764
2765 // Store the set of layers that need updates. This set must not change as
2766 // buffers are being latched, as this could result in a deadlock.
2767 // Example: Two producers share the same command stream and:
2768 // 1.) Layer 0 is latched
2769 // 2.) Layer 0 gets a new frame
2770 // 2.) Layer 1 gets a new frame
2771 // 3.) Layer 1 is latched.
2772 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2773 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002774 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002775 if (layer->hasQueuedFrame()) {
2776 frameQueued = true;
2777 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002778 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002779 } else {
2780 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002781 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002782 } else {
2783 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002784 }
Robert Carr2047fae2016-11-28 14:09:09 -08002785 });
2786
Dan Stoza9e56aa02015-11-02 13:00:03 -08002787 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002788 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002789 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002790 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002791 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002792 newDataLatched = true;
2793 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002794 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002795
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002796 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002797
2798 // If we will need to wake up at some time in the future to deal with a
2799 // queued frame that shouldn't be displayed during this vsync period, wake
2800 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002801 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002802 signalLayerUpdate();
2803 }
2804
2805 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002806 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807}
2808
Mathias Agopianad456f92011-01-13 17:53:01 -08002809void SurfaceFlinger::invalidateHwcGeometry()
2810{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002811 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002812}
2813
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002814void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2815 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002816 // We only need to actually compose the display if:
2817 // 1) It is being handled by hardware composer, which may need this to
2818 // keep its virtual display state machine in sync, or
2819 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002820 bool isHwcDisplay = display->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002821 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002822 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002823 return;
2824 }
2825
Dan Stoza9e56aa02015-11-02 13:00:03 -08002826 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002827 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002828
2829 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002830 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831}
2832
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002833bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002834 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002835
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002836 const Region bounds(display->bounds());
2837 const DisplayRenderArea renderArea(display);
2838 const auto hwcId = display->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002839 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002840 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002841
Chia-I Wu8e50e692018-05-04 10:12:37 -07002842 bool applyColorMatrix = false;
Peiyong Lin00f9c022018-05-09 15:35:33 -07002843 bool needsLegacyColorMatrix = false;
2844 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002845
Dan Stoza9e56aa02015-11-02 13:00:03 -08002846 if (hasClientComposition) {
2847 ALOGV("hasClientComposition");
2848
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002849 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002850 if (display->hasWideColorGamut()) {
2851 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002852 }
2853 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002854 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002855 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002856
Chia-I Wu8e50e692018-05-04 10:12:37 -07002857 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2858 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2859 HWC2::Capability::SkipClientColorTransform);
2860
2861 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2862 if (applyColorMatrix) {
Peiyong Lin00f9c022018-05-09 15:35:33 -07002863 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002864 }
2865
Chia-I Wubbb44462018-05-21 15:33:27 -07002866 needsLegacyColorMatrix =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002867 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2868 outputDataspace != Dataspace::UNKNOWN && outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002869
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002870 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002871 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002872 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002873 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002874
2875 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002876 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002877 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2878 }
2879 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002880 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002881
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002882 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002883 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002884 // when using overlays, we assume a fully transparent framebuffer
2885 // NOTE: we could reduce how much we need to clear, for instance
2886 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002887 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002888 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002889 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002890 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002891 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002892 // we're left with the letterbox region
2893 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002894 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002895
2896 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002897 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002898
Mathias Agopianb9494d52012-04-18 02:28:45 -07002899 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002900 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002901 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002902 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002903 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002904 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002905
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002906 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002907 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002908 // scissor on the main display. It should never be needed
2909 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002910 const Rect& bounds = display->getBounds();
2911 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002912 if (scissor != bounds) {
2913 // scissor doesn't match the screen's dimensions, so we
2914 // need to clear everything outside of it and enable
2915 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002916
Mathias Agopianf45c5102012-10-24 16:29:17 -07002917 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002918 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002919 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002920 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002921 }
2922 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002923 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002924
Mathias Agopian85d751c2012-08-29 16:59:24 -07002925 /*
2926 * and then, render the layers targeted at the framebuffer
2927 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002928
Dan Stoza9e56aa02015-11-02 13:00:03 -08002929 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002930 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002931 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002932 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002933 const Region clip(bounds.intersect(
2934 displayTransform.transform(layer->visibleRegion)));
2935 ALOGV("Layer: %s", layer->getName().string());
2936 ALOGV(" Composition type: %s",
2937 to_string(layer->getCompositionType(hwcId)).c_str());
2938 if (!clip.isEmpty()) {
2939 switch (layer->getCompositionType(hwcId)) {
2940 case HWC2::Composition::Cursor:
2941 case HWC2::Composition::Device:
2942 case HWC2::Composition::Sideband:
2943 case HWC2::Composition::SolidColor: {
2944 const Layer::State& state(layer->getDrawingState());
2945 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2946 layer->isOpaque(state) && (state.color.a == 1.0f)
2947 && hasClientComposition) {
2948 // never clear the very first layer since we're
2949 // guaranteed the FB is already cleared
2950 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002951 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002952 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002953 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002954 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002955 // switch color matrices lazily
Peiyong Lin00f9c022018-05-09 15:35:33 -07002956 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
2957 if (!legacyColorMatrixApplied) {
2958 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
2959 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002960 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07002961 } else if (legacyColorMatrixApplied) {
2962 getRenderEngine().setSaturationMatrix(mat4());
2963 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002964 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07002965
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002966 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002967 break;
2968 }
2969 default:
2970 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002971 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002972 } else {
2973 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002974 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002975 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002976 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002977
Peiyong Lin00f9c022018-05-09 15:35:33 -07002978 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002979 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002980 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07002981 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
2982 getRenderEngine().setSaturationMatrix(mat4());
2983 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002984
Mathias Agopianf45c5102012-10-24 16:29:17 -07002985 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002986 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002987 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002988}
2989
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002990void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2991 const Region& region) const {
2992 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002993 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002994 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002995}
2996
Dan Stoza7d89d062015-04-30 13:29:25 -07002997status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002998 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002999 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003000 const sp<Layer>& lbc,
3001 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003002{
Dan Stoza7d89d062015-04-30 13:29:25 -07003003 // add this layer to the current state list
3004 {
3005 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003006 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003007 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3008 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003009 return NO_MEMORY;
3010 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003011 if (parent == nullptr) {
3012 mCurrentState.layersSortedByZ.add(lbc);
3013 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003014 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003015 ALOGE("addClientLayer called with a removed parent");
3016 return NAME_NOT_FOUND;
3017 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003018 parent->addChild(lbc);
3019 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003020
Yiwei Zhang243b3782018-05-15 17:40:04 -07003021 if (gbc != nullptr) {
3022 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3023 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3024 mMaxGraphicBufferProducerListSize,
3025 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3026 mGraphicBufferProducerList.size(),
3027 mMaxGraphicBufferProducerListSize, mNumLayers);
3028 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003029 mLayersAdded = true;
3030 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003031 }
3032
Mathias Agopian96f08192010-06-02 23:28:45 -07003033 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003034 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003035
Dan Stoza7d89d062015-04-30 13:29:25 -07003036 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003037}
3038
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003039status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003040 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003041 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3042}
Robert Carr7f9b8992017-03-10 11:08:39 -08003043
chaviwca27f252018-02-06 16:46:39 -08003044status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3045 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003046 if (layer->isPendingRemoval()) {
3047 return NO_ERROR;
3048 }
3049
Robert Carr1f0a16a2016-10-24 16:27:39 -07003050 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003051 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003052 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003053 if (topLevelOnly) {
3054 return NO_ERROR;
3055 }
3056
Chia-I Wu98f1c102017-05-30 14:54:08 -07003057 sp<Layer> ancestor = p;
3058 while (ancestor->getParent() != nullptr) {
3059 ancestor = ancestor->getParent();
3060 }
3061 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3062 ALOGE("removeLayer called with a layer whose parent has been removed");
3063 return NAME_NOT_FOUND;
3064 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003065
3066 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003067 } else {
3068 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003069 }
3070
Robert Carr136e2f62017-02-08 17:54:29 -08003071 // As a matter of normal operation, the LayerCleaner will produce a second
3072 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3073 // so we will succeed in promoting it, but it's already been removed
3074 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3075 // otherwise something has gone wrong and we are leaking the layer.
3076 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003077 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3078 layer->getName().string(),
3079 (p != nullptr) ? p->getName().string() : "no-parent");
3080 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003081 } else if (index < 0) {
3082 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003083 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003084
Chia-I Wuc6657022017-08-15 11:18:17 -07003085 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003086 mLayersPendingRemoval.add(layer);
3087 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003088 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003089 setTransactionFlags(eTransactionNeeded);
3090 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091}
3092
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003093uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003094 return android_atomic_release_load(&mTransactionFlags);
3095}
3096
Mathias Agopian3f844832013-08-07 21:24:32 -07003097uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3099}
3100
Mathias Agopian3f844832013-08-07 21:24:32 -07003101uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003102 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3103}
3104
3105uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3106 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003107 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003108 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003109 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003110 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111 }
3112 return old;
3113}
3114
chaviwca27f252018-02-06 16:46:39 -08003115bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3116 for (const ComposerState& state : states) {
3117 // Here we need to check that the interface we're given is indeed
3118 // one of our own. A malicious client could give us a nullptr
3119 // IInterface, or one of its own or even one of our own but a
3120 // different type. All these situations would cause us to crash.
3121 if (state.client == nullptr) {
3122 return true;
3123 }
3124
3125 sp<IBinder> binder = IInterface::asBinder(state.client);
3126 if (binder == nullptr) {
3127 return true;
3128 }
3129
3130 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3131 return true;
3132 }
3133 }
3134 return false;
3135}
3136
Mathias Agopian8b33f032012-07-24 20:43:54 -07003137void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003138 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003139 const Vector<DisplayState>& displays,
3140 uint32_t flags)
3141{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003142 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003143 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003144 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003145
chaviwca27f252018-02-06 16:46:39 -08003146 if (containsAnyInvalidClientState(states)) {
3147 return;
3148 }
3149
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003150 if (flags & eAnimation) {
3151 // For window updates that are part of an animation we must wait for
3152 // previous animation "frames" to be handled.
3153 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003154 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003155 if (CC_UNLIKELY(err != NO_ERROR)) {
3156 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003157 // caller after a few seconds.
3158 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3159 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003160 mAnimTransactionPending = false;
3161 break;
3162 }
3163 }
3164 }
3165
chaviwca27f252018-02-06 16:46:39 -08003166 for (const DisplayState& display : displays) {
3167 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003168 }
3169
chaviwca27f252018-02-06 16:46:39 -08003170 for (const ComposerState& state : states) {
3171 transactionFlags |= setClientStateLocked(state);
3172 }
3173
3174 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3175 // as destroyed should only occur after setting all other states. This is to allow for a
3176 // child re-parent to happen before marking its original parent as destroyed (which would
3177 // then mark the child as destroyed).
3178 for (const ComposerState& state : states) {
3179 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003180 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003181
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003182 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3183 // anyway. This can be used as a flush mechanism for previous async transactions.
3184 // Empty animation transaction can be used to simulate back-pressure, so also force a
3185 // transaction for empty animation transactions.
3186 if (transactionFlags == 0 &&
3187 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003188 transactionFlags = eTransactionNeeded;
3189 }
3190
Mathias Agopian386aa982011-11-07 21:58:03 -08003191 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003192 if (mInterceptor->isEnabled()) {
3193 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003194 }
Irvel468051e2016-06-13 16:44:44 -07003195
Mathias Agopian386aa982011-11-07 21:58:03 -08003196 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003197 const auto start = (flags & eEarlyWakeup)
3198 ? VSyncModulator::TransactionStart::EARLY
3199 : VSyncModulator::TransactionStart::NORMAL;
3200 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003201
3202 // if this is a synchronous transaction, wait for it to take effect
3203 // before returning.
3204 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003205 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003206 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003207 if (flags & eAnimation) {
3208 mAnimTransactionPending = true;
3209 }
3210 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003211 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3212 if (CC_UNLIKELY(err != NO_ERROR)) {
3213 // just in case something goes wrong in SF, return to the
3214 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003215 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3216 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003217 break;
3218 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003219 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003220 }
3221}
3222
Mathias Agopiane57f2922012-08-09 16:29:12 -07003223uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3224{
Jesse Hall9a143922012-10-04 16:29:19 -07003225 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3226 if (dpyIdx < 0)
3227 return 0;
3228
Mathias Agopiane57f2922012-08-09 16:29:12 -07003229 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003230 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003231 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003232 const uint32_t what = s.what;
3233 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003234 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003235 disp.surface = s.surface;
3236 flags |= eDisplayTransactionNeeded;
3237 }
3238 }
3239 if (what & DisplayState::eLayerStackChanged) {
3240 if (disp.layerStack != s.layerStack) {
3241 disp.layerStack = s.layerStack;
3242 flags |= eDisplayTransactionNeeded;
3243 }
3244 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003245 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003246 if (disp.orientation != s.orientation) {
3247 disp.orientation = s.orientation;
3248 flags |= eDisplayTransactionNeeded;
3249 }
3250 if (disp.frame != s.frame) {
3251 disp.frame = s.frame;
3252 flags |= eDisplayTransactionNeeded;
3253 }
3254 if (disp.viewport != s.viewport) {
3255 disp.viewport = s.viewport;
3256 flags |= eDisplayTransactionNeeded;
3257 }
3258 }
Michael Lentine47e45402014-07-18 15:34:25 -07003259 if (what & DisplayState::eDisplaySizeChanged) {
3260 if (disp.width != s.width) {
3261 disp.width = s.width;
3262 flags |= eDisplayTransactionNeeded;
3263 }
3264 if (disp.height != s.height) {
3265 disp.height = s.height;
3266 flags |= eDisplayTransactionNeeded;
3267 }
3268 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003269 }
3270 return flags;
3271}
3272
chaviwca27f252018-02-06 16:46:39 -08003273uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3274 const layer_state_t& s = composerState.state;
3275 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3276
Mathias Agopian13127d82013-03-05 17:47:11 -08003277 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003278 if (layer == nullptr) {
3279 return 0;
3280 }
3281
3282 if (layer->isPendingRemoval()) {
3283 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3284 return 0;
3285 }
3286
3287 uint32_t flags = 0;
3288
3289 const uint32_t what = s.what;
3290 bool geometryAppliesWithResize =
3291 what & layer_state_t::eGeometryAppliesWithResize;
3292 if (what & layer_state_t::ePositionChanged) {
3293 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3294 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003295 }
chaviw8b3871a2017-11-01 17:41:01 -07003296 }
3297 if (what & layer_state_t::eLayerChanged) {
3298 // NOTE: index needs to be calculated before we update the state
3299 const auto& p = layer->getParent();
3300 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003301 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003302 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003303 mCurrentState.layersSortedByZ.removeAt(idx);
3304 mCurrentState.layersSortedByZ.add(layer);
3305 // we need traversal (state changed)
3306 // AND transaction (list changed)
3307 flags |= eTransactionNeeded|eTraversalNeeded;
3308 }
chaviw8b3871a2017-11-01 17:41:01 -07003309 } else {
3310 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003311 flags |= eTransactionNeeded|eTraversalNeeded;
3312 }
3313 }
chaviw8b3871a2017-11-01 17:41:01 -07003314 }
3315 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003316 // NOTE: index needs to be calculated before we update the state
3317 const auto& p = layer->getParent();
3318 if (p == nullptr) {
3319 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3320 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3321 mCurrentState.layersSortedByZ.removeAt(idx);
3322 mCurrentState.layersSortedByZ.add(layer);
3323 // we need traversal (state changed)
3324 // AND transaction (list changed)
3325 flags |= eTransactionNeeded|eTraversalNeeded;
3326 }
3327 } else {
3328 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3329 flags |= eTransactionNeeded|eTraversalNeeded;
3330 }
chaviw8b3871a2017-11-01 17:41:01 -07003331 }
3332 }
3333 if (what & layer_state_t::eSizeChanged) {
3334 if (layer->setSize(s.w, s.h)) {
3335 flags |= eTraversalNeeded;
3336 }
3337 }
3338 if (what & layer_state_t::eAlphaChanged) {
3339 if (layer->setAlpha(s.alpha))
3340 flags |= eTraversalNeeded;
3341 }
3342 if (what & layer_state_t::eColorChanged) {
3343 if (layer->setColor(s.color))
3344 flags |= eTraversalNeeded;
3345 }
3346 if (what & layer_state_t::eMatrixChanged) {
3347 if (layer->setMatrix(s.matrix))
3348 flags |= eTraversalNeeded;
3349 }
3350 if (what & layer_state_t::eTransparentRegionChanged) {
3351 if (layer->setTransparentRegionHint(s.transparentRegion))
3352 flags |= eTraversalNeeded;
3353 }
3354 if (what & layer_state_t::eFlagsChanged) {
3355 if (layer->setFlags(s.flags, s.mask))
3356 flags |= eTraversalNeeded;
3357 }
3358 if (what & layer_state_t::eCropChanged) {
3359 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3360 flags |= eTraversalNeeded;
3361 }
3362 if (what & layer_state_t::eFinalCropChanged) {
3363 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3364 flags |= eTraversalNeeded;
3365 }
3366 if (what & layer_state_t::eLayerStackChanged) {
3367 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3368 // We only allow setting layer stacks for top level layers,
3369 // everything else inherits layer stack from its parent.
3370 if (layer->hasParent()) {
3371 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3372 layer->getName().string());
3373 } else if (idx < 0) {
3374 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3375 "that also does not appear in the top level layer list. Something"
3376 " has gone wrong.", layer->getName().string());
3377 } else if (layer->setLayerStack(s.layerStack)) {
3378 mCurrentState.layersSortedByZ.removeAt(idx);
3379 mCurrentState.layersSortedByZ.add(layer);
3380 // we need traversal (state changed)
3381 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003382 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003383 }
3384 }
3385 if (what & layer_state_t::eDeferTransaction) {
3386 if (s.barrierHandle != nullptr) {
3387 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3388 } else if (s.barrierGbp != nullptr) {
3389 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3390 if (authenticateSurfaceTextureLocked(gbp)) {
3391 const auto& otherLayer =
3392 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3393 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3394 } else {
3395 ALOGE("Attempt to defer transaction to to an"
3396 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003397 }
3398 }
chaviw8b3871a2017-11-01 17:41:01 -07003399 // We don't trigger a traversal here because if no other state is
3400 // changed, we don't want this to cause any more work
3401 }
3402 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003403 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003404 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003405 if (!hadParent) {
3406 mCurrentState.layersSortedByZ.remove(layer);
3407 }
chaviw8b3871a2017-11-01 17:41:01 -07003408 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003409 }
chaviw8b3871a2017-11-01 17:41:01 -07003410 }
3411 if (what & layer_state_t::eReparentChildren) {
3412 if (layer->reparentChildren(s.reparentHandle)) {
3413 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003414 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003415 }
chaviw8b3871a2017-11-01 17:41:01 -07003416 if (what & layer_state_t::eDetachChildren) {
3417 layer->detachChildren();
3418 }
3419 if (what & layer_state_t::eOverrideScalingModeChanged) {
3420 layer->setOverrideScalingMode(s.overrideScalingMode);
3421 // We don't trigger a traversal here because if no other state is
3422 // changed, we don't want this to cause any more work
3423 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003424 return flags;
3425}
3426
chaviwca27f252018-02-06 16:46:39 -08003427void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3428 const layer_state_t& state = composerState.state;
3429 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3430
3431 sp<Layer> layer(client->getLayerUser(state.surface));
3432 if (layer == nullptr) {
3433 return;
3434 }
3435
3436 if (layer->isPendingRemoval()) {
3437 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3438 return;
3439 }
3440
3441 if (state.what & layer_state_t::eDestroySurface) {
3442 removeLayerLocked(mStateLock, layer);
3443 }
3444}
3445
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003446status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003447 const String8& name,
3448 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003449 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003450 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003451 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003452{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003453 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003454 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003455 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003456 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003457 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003458
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003459 status_t result = NO_ERROR;
3460
3461 sp<Layer> layer;
3462
Cody Northropbc755282017-03-31 12:00:08 -06003463 String8 uniqueName = getUniqueLayerName(name);
3464
Mathias Agopian3165cc22012-08-08 19:42:09 -07003465 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3466 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003467 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003468 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003469 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003470
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003471 break;
chaviw13fdc492017-06-27 12:40:18 -07003472 case ISurfaceComposerClient::eFXSurfaceColor:
3473 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003474 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003475 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003476 break;
3477 default:
3478 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003479 break;
3480 }
3481
Dan Stoza7d89d062015-04-30 13:29:25 -07003482 if (result != NO_ERROR) {
3483 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003484 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003485
Chia-I Wuab0c3192017-08-01 11:29:00 -07003486 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3487 // TODO b/64227542
3488 if (windowType == 441731) {
3489 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3490 layer->setPrimaryDisplayOnly();
3491 }
3492
Albert Chaulk479c60c2017-01-27 14:21:34 -05003493 layer->setInfo(windowType, ownerUid);
3494
Robert Carr1f0a16a2016-10-24 16:27:39 -07003495 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003496 if (result != NO_ERROR) {
3497 return result;
3498 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003499 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003500
3501 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003502 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003503}
3504
Cody Northropbc755282017-03-31 12:00:08 -06003505String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3506{
3507 bool matchFound = true;
3508 uint32_t dupeCounter = 0;
3509
3510 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3511 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3512
3513 // Loop over layers until we're sure there is no matching name
3514 while (matchFound) {
3515 matchFound = false;
3516 mDrawingState.traverseInZOrder([&](Layer* layer) {
3517 if (layer->getName() == uniqueName) {
3518 matchFound = true;
3519 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3520 }
3521 });
3522 }
3523
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003524 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3525 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003526
3527 return uniqueName;
3528}
3529
David Sodman0c69cad2017-08-21 12:12:51 -07003530status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003531 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3532 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003533{
3534 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003535 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003536 case PIXEL_FORMAT_TRANSPARENT:
3537 case PIXEL_FORMAT_TRANSLUCENT:
3538 format = PIXEL_FORMAT_RGBA_8888;
3539 break;
3540 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003541 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003542 break;
3543 }
3544
David Sodman0c69cad2017-08-21 12:12:51 -07003545 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3546 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003547 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003548 *handle = layer->getHandle();
3549 *gbp = layer->getProducer();
3550 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003551 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003552
David Sodman0c69cad2017-08-21 12:12:51 -07003553 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003554 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003555}
3556
chaviw13fdc492017-06-27 12:40:18 -07003557status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003558 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003559 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003560{
chaviw13fdc492017-06-27 12:40:18 -07003561 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003562 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003563 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003564}
3565
Mathias Agopianac9fa422013-02-11 16:40:36 -08003566status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003567{
Robert Carr9524cb32017-02-13 11:32:32 -08003568 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003569 status_t err = NO_ERROR;
3570 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003571 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003572 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003573 err = removeLayer(l);
3574 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3575 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003576 }
3577 return err;
3578}
3579
Mathias Agopian13127d82013-03-05 17:47:11 -08003580status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003581{
Mathias Agopian67106042013-03-14 19:18:13 -07003582 // called by ~LayerCleaner() when all references to the IBinder (handle)
3583 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003584 sp<Layer> l = layer.promote();
3585 if (l == nullptr) {
3586 // The layer has already been removed, carry on
3587 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003588 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003589 // If we have a parent, then we can continue to live as long as it does.
3590 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003591}
3592
Mathias Agopianb60314a2012-04-10 22:09:54 -07003593// ---------------------------------------------------------------------------
3594
Andy McFadden13a082e2012-08-24 10:16:42 -07003595void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003596 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003597 Vector<ComposerState> state;
3598 Vector<DisplayState> displays;
3599 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003600 d.what = DisplayState::eDisplayProjectionChanged |
3601 DisplayState::eLayerStackChanged;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003602 d.token = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003603 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003604 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003605 d.frame.makeInvalid();
3606 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003607 d.width = 0;
3608 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003609 displays.add(d);
3610 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003611 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3612 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003613
David Sodman105b7dc2017-11-04 20:28:14 -07003614 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003615 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003616 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003617
Brian Andersond0010582017-03-07 13:20:31 -08003618 // Use phase of 0 since phase is not known.
3619 // Use latency of 0, which will snap to the ideal latency.
3620 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003621}
3622
3623void SurfaceFlinger::initializeDisplays() {
3624 class MessageScreenInitialized : public MessageBase {
3625 SurfaceFlinger* flinger;
3626 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003627 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003628 virtual bool handler() {
3629 flinger->onInitializeDisplays();
3630 return true;
3631 }
3632 };
3633 sp<MessageBase> msg = new MessageScreenInitialized(this);
3634 postMessageAsync(msg); // we may be called from main thread, use async message
3635}
3636
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003637void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3638 bool stateLockHeld) {
3639 const int32_t displayId = display->getHwcDisplayId();
3640 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003641
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003642 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003643 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003644 return;
3645 }
3646
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003647 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003648 ALOGW("Trying to set power mode for virtual display");
3649 return;
3650 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003651
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003652 display->setPowerMode(mode);
3653
Lloyd Pique4dccc412018-01-22 17:21:36 -08003654 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003655 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003656 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003657 if (idx < 0) {
3658 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3659 return;
3660 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003661 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003662 }
3663
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003664 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003665 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003666 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003667 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003668 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003669 // FIXME: eventthread only knows about the main display right now
3670 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003671 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003672 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003673
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003674 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003675 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003676 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003677
3678 struct sched_param param = {0};
3679 param.sched_priority = 1;
3680 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3681 ALOGW("Couldn't set SCHED_FIFO on display on");
3682 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003683 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003684 // Turn off the display
3685 struct sched_param param = {0};
3686 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3687 ALOGW("Couldn't set SCHED_OTHER on display off");
3688 }
3689
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003690 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003691 disableHardwareVsync(true); // also cancels any in-progress resync
3692
Mathias Agopiancde87a32012-09-13 14:09:01 -07003693 // FIXME: eventthread only knows about the main display right now
3694 mEventThread->onScreenReleased();
3695 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003696
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003697 getHwComposer().setPowerMode(type, mode);
3698 mVisibleRegionsDirty = true;
3699 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003700 } else if (mode == HWC_POWER_MODE_DOZE ||
3701 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003702 // Update display while dozing
3703 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003704 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003705 // FIXME: eventthread only knows about the main display right now
3706 mEventThread->onScreenAcquired();
3707 resyncToHardwareVsync(true);
3708 }
3709 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3710 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003711 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003712 disableHardwareVsync(true); // also cancels any in-progress resync
3713 // FIXME: eventthread only knows about the main display right now
3714 mEventThread->onScreenReleased();
3715 }
3716 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003717 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003718 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003719 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003720 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003721
3722 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003723}
3724
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003725void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
3726 postMessageSync(new LambdaMessage([&]() {
3727 const auto display = getDisplayDevice(displayToken);
3728 if (!display) {
3729 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3730 displayToken.get());
3731 } else if (display->isVirtual()) {
3732 ALOGW("Attempt to set power mode %d for virtual display", mode);
3733 } else {
3734 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003735 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003736 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003737}
3738
3739// ---------------------------------------------------------------------------
3740
Lloyd Pique755e3192018-01-31 16:46:15 -08003741status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3742 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003743 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003744
Mathias Agopianbd115332013-04-18 16:41:04 -07003745 IPCThreadState* ipc = IPCThreadState::self();
3746 const int pid = ipc->getCallingPid();
3747 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003748
Mathias Agopianbd115332013-04-18 16:41:04 -07003749 if ((uid != AID_SHELL) &&
3750 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003751 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003752 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003753 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003754 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003755 // (this would indicate SF is stuck, but we want to be able to
3756 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003757 status_t err = mStateLock.timedLock(s2ns(1));
3758 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003759 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003760 result.appendFormat(
3761 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3762 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003763 }
3764
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003765 bool dumpAll = true;
3766 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003767 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003768
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003769 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003770 if ((index < numArgs) &&
3771 (args[index] == String16("--list"))) {
3772 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003773 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003774 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003775 }
3776
3777 if ((index < numArgs) &&
3778 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003779 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003780 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003781 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003782 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003783
3784 if ((index < numArgs) &&
3785 (args[index] == String16("--latency-clear"))) {
3786 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003787 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003788 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003789 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003790
3791 if ((index < numArgs) &&
3792 (args[index] == String16("--dispsync"))) {
3793 index++;
3794 mPrimaryDispSync.dump(result);
3795 dumpAll = false;
3796 }
Dan Stozab90cf072015-03-05 11:05:59 -08003797
3798 if ((index < numArgs) &&
3799 (args[index] == String16("--static-screen"))) {
3800 index++;
3801 dumpStaticScreenStats(result);
3802 dumpAll = false;
3803 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003804
3805 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003806 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003807 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003808 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003809 dumpAll = false;
3810 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003811
3812 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3813 index++;
3814 dumpWideColorInfo(result);
3815 dumpAll = false;
3816 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003817
3818 if ((index < numArgs) &&
3819 (args[index] == String16("--enable-layer-stats"))) {
3820 index++;
3821 mLayerStats.enable();
3822 dumpAll = false;
3823 }
3824
3825 if ((index < numArgs) &&
3826 (args[index] == String16("--disable-layer-stats"))) {
3827 index++;
3828 mLayerStats.disable();
3829 dumpAll = false;
3830 }
3831
3832 if ((index < numArgs) &&
3833 (args[index] == String16("--clear-layer-stats"))) {
3834 index++;
3835 mLayerStats.clear();
3836 dumpAll = false;
3837 }
3838
3839 if ((index < numArgs) &&
3840 (args[index] == String16("--dump-layer-stats"))) {
3841 index++;
3842 mLayerStats.dump(result);
3843 dumpAll = false;
3844 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003845
3846 if ((index < numArgs) &&
3847 (args[index] == String16("--display-identification"))) {
3848 index++;
3849 dumpDisplayIdentificationData(result);
3850 dumpAll = false;
3851 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003852
3853 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3854 index++;
3855 mTimeStats.parseArgs(asProto, args, index, result);
3856 dumpAll = false;
3857 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003858 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003859
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003860 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003861 if (asProto) {
3862 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3863 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3864 } else {
3865 dumpAllLocked(args, index, result);
3866 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003867 }
3868
Mathias Agopian9795c422009-08-26 16:36:26 -07003869 if (locked) {
3870 mStateLock.unlock();
3871 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003872 }
3873 write(fd, result.string(), result.size());
3874 return NO_ERROR;
3875}
3876
Dan Stozac7014012014-02-14 15:03:43 -08003877void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3878 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003879{
Robert Carr2047fae2016-11-28 14:09:09 -08003880 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003881 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003882 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003883}
3884
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003885void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003886 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003887{
3888 String8 name;
3889 if (index < args.size()) {
3890 name = String8(args[index]);
3891 index++;
3892 }
3893
David Sodman105b7dc2017-11-04 20:28:14 -07003894 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003895 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003896 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003897
3898 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003899 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003900 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003901 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003902 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003903 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003904 }
Robert Carr2047fae2016-11-28 14:09:09 -08003905 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003906 }
3907}
3908
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003909void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003910 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003911{
3912 String8 name;
3913 if (index < args.size()) {
3914 name = String8(args[index]);
3915 index++;
3916 }
3917
Robert Carr2047fae2016-11-28 14:09:09 -08003918 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003919 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003920 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003921 }
Robert Carr2047fae2016-11-28 14:09:09 -08003922 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003923
Svetoslavd85084b2014-03-20 10:28:31 -07003924 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003925}
3926
Jamie Gennis6547ff42013-07-16 20:12:42 -07003927// This should only be called from the main thread. Otherwise it would need
3928// the lock and should use mCurrentState rather than mDrawingState.
3929void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003930 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003931 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003932 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003933
3934 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3935}
3936
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003937void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003938{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003939 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003940
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003941 if (isLayerTripleBufferingDisabled())
3942 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003943
3944 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003945 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003946 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003947 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003948 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3949 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003950 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003951}
3952
Dan Stozab90cf072015-03-05 11:05:59 -08003953void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3954{
3955 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003956 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3957 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003958 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003959 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003960 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3961 b + 1, bucketTimeSec, percent);
3962 }
David Sodman4a36e932017-11-07 14:29:47 -08003963 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003964 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003965 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003966 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003967 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003968}
3969
Dan Stozae77c7662016-05-13 11:37:28 -07003970void SurfaceFlinger::recordBufferingStats(const char* layerName,
3971 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003972 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3973 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003974 for (const auto& segment : history) {
3975 if (!segment.usedThirdBuffer) {
3976 stats.twoBufferTime += segment.totalTime;
3977 }
3978 if (segment.occupancyAverage < 1.0f) {
3979 stats.doubleBufferedTime += segment.totalTime;
3980 } else if (segment.occupancyAverage < 2.0f) {
3981 stats.tripleBufferedTime += segment.totalTime;
3982 }
3983 ++stats.numSegments;
3984 stats.totalTime += segment.totalTime;
3985 }
3986}
3987
Brian Andersond6927fb2016-07-23 23:37:30 -07003988void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3989 result.appendFormat("Layer frame timestamps:\n");
3990
3991 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3992 const size_t count = currentLayers.size();
3993 for (size_t i=0 ; i<count ; i++) {
3994 currentLayers[i]->dumpFrameEvents(result);
3995 }
3996}
3997
Dan Stozae77c7662016-05-13 11:37:28 -07003998void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3999 result.append("Buffering stats:\n");
4000 result.append(" [Layer name] <Active time> <Two buffer> "
4001 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004002 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004003 typedef std::tuple<std::string, float, float, float> BufferTuple;
4004 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004005 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004006 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004007 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004008 if (stats.numSegments == 0) {
4009 continue;
4010 }
4011 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4012 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4013 stats.totalTime;
4014 float doubleBufferRatio = static_cast<float>(
4015 stats.doubleBufferedTime) / stats.totalTime;
4016 float tripleBufferRatio = static_cast<float>(
4017 stats.tripleBufferedTime) / stats.totalTime;
4018 sorted.insert({activeTime, {name, twoBufferRatio,
4019 doubleBufferRatio, tripleBufferRatio}});
4020 }
4021 for (const auto& sortedPair : sorted) {
4022 float activeTime = sortedPair.first;
4023 const BufferTuple& values = sortedPair.second;
4024 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4025 std::get<0>(values).c_str(), activeTime,
4026 std::get<1>(values), std::get<2>(values),
4027 std::get<3>(values));
4028 }
4029 result.append("\n");
4030}
4031
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004032void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004033 for (size_t i = 0; i < mDisplays.size(); ++i) {
4034 const auto& display = mDisplays[i];
4035 const int32_t hwcId = display->getHwcDisplayId();
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004036 const auto displayId = getHwComposer().getHwcDisplayId(hwcId);
4037 if (!displayId) {
4038 continue;
4039 }
4040
4041 result.appendFormat("Display %d: ", hwcId);
4042 uint8_t port;
4043 DisplayIdentificationData data;
4044 if (!getHwComposer().getDisplayIdentificationData(*displayId, &port, &data)) {
4045 result.append("no identification data\n");
4046 continue;
4047 }
4048
4049 if (!isEdid(data)) {
4050 result.append("unknown identification data: ");
4051 for (uint8_t byte : data) {
4052 result.appendFormat("%x ", byte);
4053 }
4054 result.append("\n");
4055 continue;
4056 }
4057
4058 const auto edid = parseEdid(data);
4059 if (!edid) {
4060 result.append("invalid EDID: ");
4061 for (uint8_t byte : data) {
4062 result.appendFormat("%x ", byte);
4063 }
4064 result.append("\n");
4065 continue;
4066 }
4067
4068 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4069 result.append(edid->displayName.data(), edid->displayName.length());
4070 result.append("\"\n");
4071 }
4072 result.append("\n");
4073}
4074
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004075void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4076 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004077 result.appendFormat("DisplayColorSetting: %s\n",
4078 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004079
4080 // TODO: print out if wide-color mode is active or not
4081
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004082 for (size_t i = 0; i < mDisplays.size(); ++i) {
4083 const auto& display = mDisplays[i];
4084 const int32_t hwcId = display->getHwcDisplayId();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004085 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4086 continue;
4087 }
4088
4089 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004090 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004091 for (auto&& mode : modes) {
4092 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4093 }
4094
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004095 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004096 result.appendFormat(" Current color mode: %s (%d)\n",
4097 decodeColorMode(currentMode).c_str(), currentMode);
4098 }
4099 result.append("\n");
4100}
4101
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004102LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004103 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004104 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4105 const State& state = useDrawing ? mDrawingState : mCurrentState;
4106 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004107 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004108 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004109 });
4110
4111 return layersProto;
4112}
4113
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004114LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004115 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004116
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004117 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004118 resolution->set_w(display.getWidth());
4119 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004120
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004121 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4122 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4123 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004124
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004125 const int32_t hwcId = display.getHwcDisplayId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004126 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004127 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004128 LayerProto* layerProto = layersProto.add_layers();
4129 layer->writeToProto(layerProto, hwcId);
4130 }
4131 });
4132
4133 return layersProto;
4134}
4135
Mathias Agopian74d211a2013-04-22 16:55:35 +02004136void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4137 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004138{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004139 bool colorize = false;
4140 if (index < args.size()
4141 && (args[index] == String16("--color"))) {
4142 colorize = true;
4143 index++;
4144 }
4145
4146 Colorizer colorizer(colorize);
4147
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004148 // figure out if we're stuck somewhere
4149 const nsecs_t now = systemTime();
4150 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4151 const nsecs_t inTransaction(mDebugInTransaction);
4152 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4153 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4154
4155 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004156 * Dump library configuration.
4157 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004158
4159 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004160 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004161 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004162 appendSfConfigString(result);
4163 appendUiConfigString(result);
4164 appendGuiConfigString(result);
4165 result.append("\n");
4166
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004167 result.append("\nDisplay identification data:\n");
4168 dumpDisplayIdentificationData(result);
4169
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004170 result.append("\nWide-Color information:\n");
4171 dumpWideColorInfo(result);
4172
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004173 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004174 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004175 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004176 result.append(SyncFeatures::getInstance().toString());
4177 result.append("\n");
4178
David Sodman105b7dc2017-11-04 20:28:14 -07004179 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004180
Andy McFadden41d67d72014-04-25 16:58:34 -07004181 colorizer.bold(result);
4182 result.append("DispSync configuration: ");
4183 colorizer.reset(result);
Dan Stoza84d619e2018-03-28 17:07:36 -07004184 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4185 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4186 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004187 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004188 result.append("\n");
4189
Dan Stozab90cf072015-03-05 11:05:59 -08004190 // Dump static screen stats
4191 result.append("\n");
4192 dumpStaticScreenStats(result);
4193 result.append("\n");
4194
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004195 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4196
Dan Stozae77c7662016-05-13 11:37:28 -07004197 dumpBufferingStats(result);
4198
Andy McFadden4803b742012-09-24 19:07:20 -07004199 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004200 * Dump the visible layer list
4201 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004202 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004203 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004204 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4205 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004206 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004207
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004208 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004209 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004210 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004211 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004212
4213 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004214 * Dump Display state
4215 */
4216
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004217 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004218 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004219 colorizer.reset(result);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004220 for (size_t i = 0; i < mDisplays.size(); ++i) {
4221 const auto& display = mDisplays[i];
4222 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004223 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004224 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004225
4226 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004227 * Dump SurfaceFlinger global state
4228 */
4229
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004230 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004231 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004232 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004233
Mathias Agopian888c8222012-08-04 21:10:38 -07004234 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004235 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004236
David Sodmanbc815282017-11-05 18:57:52 -08004237 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004238
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004239 if (display) {
4240 display->undefinedRegion.dump(result, "undefinedRegion");
4241 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4242 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004243 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004244 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004245 " last eglSwapBuffers() time: %f us\n"
4246 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004247 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004248 " refresh-rate : %f fps\n"
4249 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004250 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004251 " gpu_to_cpu_unsupported : %d\n"
4252 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004253 mLastSwapBufferTime/1000.0,
4254 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004255 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004256 1e9 / activeConfig->getVsyncPeriod(),
4257 activeConfig->getDpiX(),
4258 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004259 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004260
Mathias Agopian74d211a2013-04-22 16:55:35 +02004261 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004262 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004263
Mathias Agopian74d211a2013-04-22 16:55:35 +02004264 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004265 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004266
4267 /*
4268 * VSYNC state
4269 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004270 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004271 result.append("\n");
4272
4273 /*
4274 * HWC layer minidump
4275 */
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004276 for (size_t i = 0; i < mDisplays.size(); ++i) {
4277 const auto& display = mDisplays[i];
4278 const int32_t hwcId = display->getHwcDisplayId();
Dan Stozae22aec72016-08-01 13:20:59 -07004279 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4280 continue;
4281 }
4282
4283 result.appendFormat("Display %d HWC layers:\n", hwcId);
4284 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004285 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004286 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004287 });
Dan Stozae22aec72016-08-01 13:20:59 -07004288 result.append("\n");
4289 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004290
4291 /*
4292 * Dump HWComposer state
4293 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004294 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004295 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004296 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004297 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004298 result.appendFormat(" h/w composer %s\n",
4299 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004300 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004301
4302 /*
4303 * Dump gralloc state
4304 */
4305 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4306 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004307
4308 /*
4309 * Dump VrFlinger state if in use.
4310 */
4311 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4312 result.append("VrFlinger state:\n");
4313 result.append(mVrFlinger->Dump().c_str());
4314 result.append("\n");
4315 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004316}
4317
Mathias Agopian13127d82013-03-05 17:47:11 -08004318const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004319SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004320 // Note: mStateLock is held here
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004321 wp<IBinder> displayToken;
4322 for (size_t i = 0; i < mDisplays.size(); ++i) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004323 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004324 displayToken = mDisplays.keyAt(i);
Jesse Hall48bc05b2013-03-21 14:06:52 -07004325 break;
4326 }
4327 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004328 if (displayToken == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004329 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4330 // Just use the primary display so we have something to return
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004331 displayToken = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
Jesse Hall48bc05b2013-03-21 14:06:52 -07004332 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004333 return getDisplayDeviceLocked(displayToken)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004334}
4335
Keun young Park63f165f2012-08-31 10:53:36 -07004336bool SurfaceFlinger::startDdmConnection()
4337{
4338 void* libddmconnection_dso =
4339 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4340 if (!libddmconnection_dso) {
4341 return false;
4342 }
4343 void (*DdmConnection_start)(const char* name);
4344 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004345 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004346 if (!DdmConnection_start) {
4347 dlclose(libddmconnection_dso);
4348 return false;
4349 }
4350 (*DdmConnection_start)(getServiceName());
4351 return true;
4352}
4353
Chia-I Wu28f320b2018-05-03 11:02:56 -07004354void SurfaceFlinger::updateColorMatrixLocked() {
4355 mat4 colorMatrix;
4356 if (mGlobalSaturationFactor != 1.0f) {
4357 // Rec.709 luma coefficients
4358 float3 luminance{0.213f, 0.715f, 0.072f};
4359 luminance *= 1.0f - mGlobalSaturationFactor;
4360 mat4 saturationMatrix = mat4(
4361 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4362 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4363 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4364 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4365 );
4366 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4367 } else {
4368 colorMatrix = mClientColorMatrix * mDaltonizer();
4369 }
4370
4371 if (mCurrentState.colorMatrix != colorMatrix) {
4372 mCurrentState.colorMatrix = colorMatrix;
4373 mCurrentState.colorMatrixChanged = true;
4374 setTransactionFlags(eTransactionNeeded);
4375 }
4376}
4377
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004378status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004379 switch (code) {
4380 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004381 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004382 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004383 case CLEAR_ANIMATION_FRAME_STATS:
4384 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004385 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004386 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004387 case ENABLE_VSYNC_INJECTIONS:
4388 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004389 {
4390 // codes that require permission check
4391 IPCThreadState* ipc = IPCThreadState::self();
4392 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004393 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004394 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004395 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004396 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004397 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004398 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004399 break;
4400 }
Robert Carr1db73f62016-12-21 12:58:51 -08004401 /*
4402 * Calling setTransactionState is safe, because you need to have been
4403 * granted a reference to Client* and Handle* to do anything with it.
4404 *
4405 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4406 */
4407 case SET_TRANSACTION_STATE:
4408 case CREATE_SCOPED_CONNECTION:
4409 {
4410 return OK;
4411 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004412 case CAPTURE_SCREEN:
4413 {
4414 // codes that require permission check
4415 IPCThreadState* ipc = IPCThreadState::self();
4416 const int pid = ipc->getCallingPid();
4417 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004418 if ((uid != AID_GRAPHICS) &&
4419 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004420 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004421 return PERMISSION_DENIED;
4422 }
4423 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004424 }
chaviwa76b2712017-09-20 12:02:26 -07004425 case CAPTURE_LAYERS: {
4426 IPCThreadState* ipc = IPCThreadState::self();
4427 const int pid = ipc->getCallingPid();
4428 const int uid = ipc->getCallingUid();
4429 if ((uid != AID_GRAPHICS) &&
4430 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4431 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4432 return PERMISSION_DENIED;
4433 }
4434 break;
4435 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004436 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004437 return OK;
4438}
4439
4440status_t SurfaceFlinger::onTransact(
4441 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4442{
4443 status_t credentialCheck = CheckTransactCodeCredentials(code);
4444 if (credentialCheck != OK) {
4445 return credentialCheck;
4446 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004447
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004448 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4449 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004450 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004451 IPCThreadState* ipc = IPCThreadState::self();
4452 const int uid = ipc->getCallingUid();
4453 if (CC_UNLIKELY(uid != AID_SYSTEM
4454 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004455 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004456 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004457 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004458 return PERMISSION_DENIED;
4459 }
4460 int n;
4461 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004462 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004463 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004464 return NO_ERROR;
4465 case 1002: // SHOW_UPDATES
4466 n = data.readInt32();
4467 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004468 invalidateHwcGeometry();
4469 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004470 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004471 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004472 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004473 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004474 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004475 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004476 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004477 setTransactionFlags(
4478 eTransactionNeeded|
4479 eDisplayTransactionNeeded|
4480 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004481 return NO_ERROR;
4482 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004483 case 1006:{ // send empty update
4484 signalRefresh();
4485 return NO_ERROR;
4486 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004487 case 1008: // toggle use of hw composer
4488 n = data.readInt32();
4489 mDebugDisableHWC = n ? 1 : 0;
4490 invalidateHwcGeometry();
4491 repaintEverything();
4492 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004493 case 1009: // toggle use of transform hint
4494 n = data.readInt32();
4495 mDebugDisableTransformHint = n ? 1 : 0;
4496 invalidateHwcGeometry();
4497 repaintEverything();
4498 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004499 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004500 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004501 reply->writeInt32(0);
4502 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004503 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004504 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004505 return NO_ERROR;
4506 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004507 const auto display = getDefaultDisplayDevice();
4508 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004509 return NO_ERROR;
4510 }
4511 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004512 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004513 // daltonize
4514 n = data.readInt32();
4515 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004516 case 1:
4517 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4518 break;
4519 case 2:
4520 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4521 break;
4522 case 3:
4523 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4524 break;
4525 default:
4526 mDaltonizer.setType(ColorBlindnessType::None);
4527 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004528 }
4529 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004530 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004531 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004532 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004533 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004534
4535 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004536 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004537 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004538 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004539 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004540 // apply a color matrix
4541 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004542 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004543 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004544 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004545 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004546 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004547 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004548 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004549 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004550 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004551 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004552
4553 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4554 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004555 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004556 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4557 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4558 }
4559
Chia-I Wu28f320b2018-05-03 11:02:56 -07004560 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004561 return NO_ERROR;
4562 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004563 // This is an experimental interface
4564 // Needs to be shifted to proper binder interface when we productize
4565 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004566 n = data.readInt32();
4567 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004568 return NO_ERROR;
4569 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004570 case 1017: {
4571 n = data.readInt32();
4572 mForceFullDamage = static_cast<bool>(n);
4573 return NO_ERROR;
4574 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004575 case 1018: { // Modify Choreographer's phase offset
4576 n = data.readInt32();
4577 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4578 return NO_ERROR;
4579 }
4580 case 1019: { // Modify SurfaceFlinger's phase offset
4581 n = data.readInt32();
4582 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4583 return NO_ERROR;
4584 }
Irvel468051e2016-06-13 16:44:44 -07004585 case 1020: { // Layer updates interceptor
4586 n = data.readInt32();
4587 if (n) {
4588 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004589 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004590 }
4591 else{
4592 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004593 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004594 }
4595 return NO_ERROR;
4596 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004597 case 1021: { // Disable HWC virtual displays
4598 n = data.readInt32();
4599 mUseHwcVirtualDisplays = !n;
4600 return NO_ERROR;
4601 }
Romain Guy0147a172017-06-01 13:53:56 -07004602 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004603 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004604 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004605
Chia-I Wu28f320b2018-05-03 11:02:56 -07004606 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004607 return NO_ERROR;
4608 }
Romain Guy54f154a2017-10-24 21:40:32 +01004609 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004610 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004611 invalidateHwcGeometry();
4612 repaintEverything();
4613 return NO_ERROR;
4614 }
4615 case 1024: { // Is wide color gamut rendering/color management supported?
4616 reply->writeBool(hasWideColorDisplay);
4617 return NO_ERROR;
4618 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004619 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004620 n = data.readInt32();
4621 if (n) {
4622 ALOGV("LayerTracing enabled");
4623 mTracing.enable();
4624 doTracing("tracing.enable");
4625 reply->writeInt32(NO_ERROR);
4626 } else {
4627 ALOGV("LayerTracing disabled");
4628 status_t err = mTracing.disable();
4629 reply->writeInt32(err);
4630 }
4631 return NO_ERROR;
4632 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004633 case 1026: { // Get layer tracing status
4634 reply->writeBool(mTracing.isEnabled());
4635 return NO_ERROR;
4636 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004637 // Is a DisplayColorSetting supported?
4638 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004639 const auto display = getDefaultDisplayDevice();
4640 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004641 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004642 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004643
4644 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4645 switch (setting) {
4646 case DisplayColorSetting::MANAGED:
4647 reply->writeBool(hasWideColorDisplay);
4648 break;
4649 case DisplayColorSetting::UNMANAGED:
4650 reply->writeBool(true);
4651 break;
4652 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004653 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004654 break;
4655 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004656 reply->writeBool(
4657 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004658 break;
4659 }
4660 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004661 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004662 }
4663 }
4664 return err;
4665}
4666
Steven Thomas6d8110b2017-08-31 18:24:21 -07004667void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004668 android_atomic_or(1, &mRepaintEverything);
4669 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004670}
4671
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004672// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4673class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004674public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004675 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4676 ~WindowDisconnector() {
4677 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004678 }
4679
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004680private:
4681 ANativeWindow* mWindow;
4682 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004683};
4684
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004685status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4686 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4687 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4688 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004689 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004690 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004691
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004692 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004693
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004694 const auto display = getDisplayDeviceLocked(displayToken);
4695 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004696
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004697 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004698
4699 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004700 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004701 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004702}
4703
4704status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004705 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004706 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004707 ATRACE_CALL();
4708
4709 class LayerRenderArea : public RenderArea {
4710 public:
Robert Carr578038f2018-03-09 12:25:24 -08004711 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4712 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004713 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004714 mLayer(layer),
4715 mCrop(crop),
4716 mFlinger(flinger),
4717 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004718 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004719 Rect getBounds() const override {
4720 const Layer::State& layerState(mLayer->getDrawingState());
4721 return Rect(layerState.active.w, layerState.active.h);
4722 }
4723 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4724 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4725 bool isSecure() const override { return false; }
4726 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004727 Rect getSourceCrop() const override {
4728 if (mCrop.isEmpty()) {
4729 return getBounds();
4730 } else {
4731 return mCrop;
4732 }
4733 }
Robert Carr578038f2018-03-09 12:25:24 -08004734 class ReparentForDrawing {
4735 public:
4736 const sp<Layer>& oldParent;
4737 const sp<Layer>& newParent;
4738
4739 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4740 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004741 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004742 }
Robert Carr15eae092018-03-23 13:43:53 -07004743 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004744 };
4745
4746 void render(std::function<void()> drawLayers) override {
4747 if (!mChildrenOnly) {
4748 mTransform = mLayer->getTransform().inverse();
4749 drawLayers();
4750 } else {
4751 Rect bounds = getBounds();
4752 screenshotParentLayer =
4753 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4754 bounds.getWidth(), bounds.getHeight(), 0);
4755
4756 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4757 drawLayers();
4758 }
4759 }
chaviwa76b2712017-09-20 12:02:26 -07004760
chaviwa76b2712017-09-20 12:02:26 -07004761 private:
chaviw7206d492017-11-10 16:16:12 -08004762 const sp<Layer> mLayer;
4763 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004764
4765 // In the "childrenOnly" case we reparent the children to a screenshot
4766 // layer which has no properties set and which does not draw.
4767 sp<ContainerLayer> screenshotParentLayer;
4768 Transform mTransform;
4769
4770 SurfaceFlinger* mFlinger;
4771 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004772 };
4773
4774 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4775 auto parent = layerHandle->owner.promote();
4776
chaviw7206d492017-11-10 16:16:12 -08004777 if (parent == nullptr || parent->isPendingRemoval()) {
4778 ALOGE("captureLayers called with a removed parent");
4779 return NAME_NOT_FOUND;
4780 }
4781
Robert Carr578038f2018-03-09 12:25:24 -08004782 const int uid = IPCThreadState::self()->getCallingUid();
4783 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4784 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4785 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4786 return PERMISSION_DENIED;
4787 }
4788
chaviw7206d492017-11-10 16:16:12 -08004789 Rect crop(sourceCrop);
4790 if (sourceCrop.width() <= 0) {
4791 crop.left = 0;
4792 crop.right = parent->getCurrentState().active.w;
4793 }
4794
4795 if (sourceCrop.height() <= 0) {
4796 crop.top = 0;
4797 crop.bottom = parent->getCurrentState().active.h;
4798 }
4799
4800 int32_t reqWidth = crop.width() * frameScale;
4801 int32_t reqHeight = crop.height() * frameScale;
4802
Robert Carr578038f2018-03-09 12:25:24 -08004803 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004804
Robert Carr578038f2018-03-09 12:25:24 -08004805 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004806 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4807 if (!layer->isVisible()) {
4808 return;
Robert Carr578038f2018-03-09 12:25:24 -08004809 } else if (childrenOnly && layer == parent.get()) {
4810 return;
chaviwa76b2712017-09-20 12:02:26 -07004811 }
4812 visitor(layer);
4813 });
4814 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004815 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004816}
4817
4818status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4819 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004820 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004821 bool useIdentityTransform) {
4822 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004823
Iris Chang7501ed62018-04-30 14:45:42 +08004824 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004825
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004826 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4827 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4828 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4829 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004830
4831 // This mutex protects syncFd and captureResult for communication of the return values from the
4832 // main thread back to this Binder thread
4833 std::mutex captureMutex;
4834 std::condition_variable captureCondition;
4835 std::unique_lock<std::mutex> captureLock(captureMutex);
4836 int syncFd = -1;
4837 std::optional<status_t> captureResult;
4838
Robert Carr03480e22018-01-04 16:02:06 -08004839 const int uid = IPCThreadState::self()->getCallingUid();
4840 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4841
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004842 sp<LambdaMessage> message = new LambdaMessage([&]() {
4843 // If there is a refresh pending, bug out early and tell the binder thread to try again
4844 // after the refresh.
4845 if (mRefreshPending) {
4846 ATRACE_NAME("Skipping screenshot for now");
4847 std::unique_lock<std::mutex> captureLock(captureMutex);
4848 captureResult = std::make_optional<status_t>(EAGAIN);
4849 captureCondition.notify_one();
4850 return;
4851 }
4852
4853 status_t result = NO_ERROR;
4854 int fd = -1;
4855 {
4856 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004857 renderArea.render([&]() {
4858 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4859 useIdentityTransform, forSystem, &fd);
4860 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004861 }
4862
4863 {
4864 std::unique_lock<std::mutex> captureLock(captureMutex);
4865 syncFd = fd;
4866 captureResult = std::make_optional<status_t>(result);
4867 captureCondition.notify_one();
4868 }
4869 });
4870
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004871 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004872 if (result == NO_ERROR) {
4873 captureCondition.wait(captureLock, [&]() { return captureResult; });
4874 while (*captureResult == EAGAIN) {
4875 captureResult.reset();
4876 result = postMessageAsync(message);
4877 if (result != NO_ERROR) {
4878 return result;
4879 }
4880 captureCondition.wait(captureLock, [&]() { return captureResult; });
4881 }
4882 result = *captureResult;
4883 }
4884
4885 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004886 sync_wait(syncFd, -1);
4887 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004888 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004889
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004890 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004891}
4892
chaviwa76b2712017-09-20 12:02:26 -07004893void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4894 TraverseLayersFunction traverseLayers, bool yswap,
4895 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004896 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004897
Lloyd Pique144e1162017-12-20 16:44:52 -08004898 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004899
4900 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004901 const auto raWidth = renderArea.getWidth();
4902 const auto raHeight = renderArea.getHeight();
4903
4904 const auto reqWidth = renderArea.getReqWidth();
4905 const auto reqHeight = renderArea.getReqHeight();
4906 Rect sourceCrop = renderArea.getSourceCrop();
4907
Iris Chang7501ed62018-04-30 14:45:42 +08004908 bool filtering = false;
4909 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4910 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
4911 static_cast<int32_t>(reqHeight) != raWidth;
4912 } else {
4913 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4914 static_cast<int32_t>(reqHeight) != raHeight;
4915 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004916
Dan Stozac1879002014-05-22 15:59:05 -07004917 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004918 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004919 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004920 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08004921 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4922 Transform tr;
4923 uint32_t flags = 0x00;
4924 switch (mPrimaryDisplayOrientation) {
4925 case DisplayState::eOrientation90:
4926 flags = Transform::ROT_90;
4927 break;
4928 case DisplayState::eOrientation180:
4929 flags = Transform::ROT_180;
4930 break;
4931 case DisplayState::eOrientation270:
4932 flags = Transform::ROT_270;
4933 break;
4934 }
4935 tr.set(flags, raWidth, raHeight);
4936 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07004937 }
4938
4939 // ensure that sourceCrop is inside screen
4940 if (sourceCrop.left < 0) {
4941 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4942 }
chaviwa76b2712017-09-20 12:02:26 -07004943 if (sourceCrop.right > raWidth) {
4944 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004945 }
4946 if (sourceCrop.top < 0) {
4947 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4948 }
chaviwa76b2712017-09-20 12:02:26 -07004949 if (sourceCrop.bottom > raHeight) {
4950 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004951 }
4952
Chia-I Wu36574d92018-05-16 10:54:36 -07004953 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
4954 engine.setOutputDataSpace(Dataspace::SRGB);
4955 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07004956
Mathias Agopian180f10d2013-04-10 22:55:41 -07004957 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004958 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004959
Iris Chang7501ed62018-04-30 14:45:42 +08004960 Transform::orientation_flags rotation = renderArea.getRotationFlags();
4961 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4962 // convert hw orientation into flag presentation
4963 // here inverse transform needed
4964 uint8_t hw_rot_90 = 0x00;
4965 uint8_t hw_flip_hv = 0x00;
4966 switch (mPrimaryDisplayOrientation) {
4967 case DisplayState::eOrientation90:
4968 hw_rot_90 = Transform::ROT_90;
4969 hw_flip_hv = Transform::ROT_180;
4970 break;
4971 case DisplayState::eOrientation180:
4972 hw_flip_hv = Transform::ROT_180;
4973 break;
4974 case DisplayState::eOrientation270:
4975 hw_rot_90 = Transform::ROT_90;
4976 break;
4977 }
4978
4979 // transform flags operation
4980 // 1) flip H V if both have ROT_90 flag
4981 // 2) XOR these flags
4982 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
4983 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
4984 if (rotation_rot_90 & hw_rot_90) {
4985 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
4986 }
4987 rotation = static_cast<Transform::orientation_flags>
4988 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
4989 }
4990
Mathias Agopian180f10d2013-04-10 22:55:41 -07004991 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004992 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08004993 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004994 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004995
chaviw50da5042018-04-09 13:49:37 -07004996 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004997 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004998 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004999
chaviwa76b2712017-09-20 12:02:26 -07005000 traverseLayers([&](Layer* layer) {
5001 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07005002 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005003 if (filtering) layer->setFiltering(false);
5004 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005005}
5006
chaviwa76b2712017-09-20 12:02:26 -07005007status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5008 TraverseLayersFunction traverseLayers,
5009 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005010 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005011 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005012 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005013 ATRACE_CALL();
5014
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005015 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005016
5017 traverseLayers([&](Layer* layer) {
5018 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5019 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005020
Robert Carr03480e22018-01-04 16:02:06 -08005021 // We allow the system server to take screenshots of secure layers for
5022 // use in situations like the Screen-rotation animation and place
5023 // the impetus on WindowManager to not persist them.
5024 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005025 ALOGW("FB is protected: PERMISSION_DENIED");
5026 return PERMISSION_DENIED;
5027 }
5028
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005029 // this binds the given EGLImage as a framebuffer for the
5030 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005031 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005032 if (bufferBond.getStatus() != NO_ERROR) {
5033 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005034 return INVALID_OPERATION;
5035 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005036
Dan Stozaabcda352017-06-01 14:37:39 -07005037 // this will in fact render into our dequeued buffer
5038 // via an FBO, which means we didn't have to create
5039 // an EGLSurface and therefore we're not
5040 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005041 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005042
Dan Stozaabcda352017-06-01 14:37:39 -07005043 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005044 getRenderEngine().finish();
5045 *outSyncFd = -1;
5046
chaviwa76b2712017-09-20 12:02:26 -07005047 const auto reqWidth = renderArea.getReqWidth();
5048 const auto reqHeight = renderArea.getReqHeight();
5049
Dan Stozaabcda352017-06-01 14:37:39 -07005050 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5051 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005052 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005053 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005054 } else {
5055 base::unique_fd syncFd = getRenderEngine().flush();
5056 if (syncFd < 0) {
5057 getRenderEngine().finish();
5058 }
5059 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005060 }
5061
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005062 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005063}
5064
Mathias Agopiand5556842013-09-19 17:08:37 -07005065void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005066 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005067 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005068 for (size_t y = 0; y < h; y++) {
5069 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5070 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005071 if (p[x] != 0xFF000000) return;
5072 }
5073 }
chaviwa76b2712017-09-20 12:02:26 -07005074 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005075
Robert Carr2047fae2016-11-28 14:09:09 -08005076 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005077 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005078 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005079 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5080 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5081 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5082 static_cast<float>(state.color.a));
5083 i++;
5084 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005085 }
5086}
5087
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005088// ---------------------------------------------------------------------------
5089
Dan Stoza412903f2017-04-27 13:42:17 -07005090void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5091 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005092}
5093
Dan Stoza412903f2017-04-27 13:42:17 -07005094void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5095 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005096}
5097
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005098void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5099 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005100 const LayerVector::Visitor& visitor) {
5101 // We loop through the first level of layers without traversing,
5102 // as we need to interpret min/max layer Z in the top level Z space.
5103 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005104 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005105 continue;
5106 }
5107 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005108 // relative layers are traversed in Layer::traverseInZOrder
5109 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005110 continue;
5111 }
5112 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005113 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005114 return;
5115 }
chaviwa76b2712017-09-20 12:02:26 -07005116 if (!layer->isVisible()) {
5117 return;
5118 }
5119 visitor(layer);
5120 });
5121 }
5122}
5123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005124}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005125
Chia-I Wu30505fb2018-03-26 16:20:31 -07005126
Mathias Agopian3f844832013-08-07 21:24:32 -07005127#if defined(__gl_h_)
5128#error "don't include gl/gl.h in this file"
5129#endif
5130
5131#if defined(__gl2_h_)
5132#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005133#endif