blob: 2a2be83a8a80be45ac73450584fee838d1cd21de [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include "Effects/Daltonizer.h"
87
Mathias Agopian875d8e12013-06-07 15:35:48 -070088#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070089#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070090
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080092#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
93#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090094#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090095
chaviw1d044282017-09-27 12:19:28 -070096#include <layerproto/LayerProtoParser.h>
97
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080098#define DISPLAY_COUNT 1
99
Mathias Agopianfee2b462013-07-03 12:34:01 -0700100/*
101 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
102 * black pixels.
103 */
104#define DEBUG_SCREENSHOTS false
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107
Jaesoo Lee43518572017-01-23 19:03:16 +0900108using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700110using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700111using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700112using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700113using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
Steven Thomasb02664d2017-07-26 18:48:28 -0700115namespace {
116class ConditionalLock {
117public:
118 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
119 if (lock) {
120 mMutex.lock();
121 }
122 }
123 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
124private:
125 Mutex& mMutex;
126 bool mLocked;
127};
128} // namespace anonymous
129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130// ---------------------------------------------------------------------------
131
Mathias Agopian99b49842011-06-27 16:05:52 -0700132const String16 sHardwareTest("android.permission.HARDWARE_TEST");
133const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
134const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
135const String16 sDump("android.permission.DUMP");
136
137// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800138int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
139int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700140int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700141bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800142uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800143bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800144bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800145int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800146// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600147bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700148
Kalle Raitaa099a242017-01-11 11:17:29 -0800149
150std::string getHwcServiceName() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.hwc_service_name", value, "default");
153 ALOGI("Using HWComposer service: '%s'", value);
154 return std::string(value);
155}
156
157bool useTrebleTestingOverride() {
158 char value[PROPERTY_VALUE_MAX] = {};
159 property_get("debug.sf.treble_testing_override", value, "false");
160 ALOGI("Treble testing override: '%s'", value);
161 return std::string(value) == "true";
162}
163
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800164std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
165 switch(displayColorSetting) {
166 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700167 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800168 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700169 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800170 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700171 return std::string("Enhanced");
172 default:
173 return std::string("Unknown ") +
174 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800175 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800176}
177
Lloyd Pique99d3da52018-01-22 17:48:03 -0800178NativeWindowSurface::~NativeWindowSurface() = default;
179
180namespace impl {
181
182class NativeWindowSurface final : public android::NativeWindowSurface {
183public:
184 static std::unique_ptr<android::NativeWindowSurface> create(
185 const sp<IGraphicBufferProducer>& producer) {
186 return std::make_unique<NativeWindowSurface>(producer);
187 }
188
189 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
190 : surface(new Surface(producer, false)) {}
191
192 ~NativeWindowSurface() override = default;
193
194private:
195 sp<ANativeWindow> getNativeWindow() const override { return surface; }
196
197 void preallocateBuffers() override { surface->allocateBuffers(); }
198
199 sp<Surface> surface;
200};
201
202} // namespace impl
203
David Sodmanbc815282017-11-05 18:57:52 -0800204SurfaceFlingerBE::SurfaceFlingerBE()
205 : mHwcServiceName(getHwcServiceName()),
206 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800207 mFrameBuckets(),
208 mTotalTime(0),
209 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800210 mComposerSequenceId(0) {
211}
212
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800213SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800214 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800215 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700216 mTransactionPending(false),
217 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700218 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700219 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700220 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800221 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700222 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800224 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800225 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700227 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700228 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700229 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700230 mDebugInSwapBuffers(0),
231 mLastSwapBufferTime(0),
232 mDebugInTransaction(0),
233 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700234 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700235 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000236 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700237 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700238 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800239 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800240 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700241 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800242 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800243 mCreateBufferQueue(&BufferQueue::createBufferQueue),
244 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800245
246SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800247 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800248
249 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
250 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
251
252 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
253 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
254
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800255 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
256 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700258 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
259 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
260
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700261 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
262 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
263
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800264 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
265 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
266
Steven Thomas050b2c82017-03-06 11:45:16 -0800267 // Vr flinger is only enabled on Daydream ready devices.
268 useVrFlinger = getBool< ISurfaceFlingerConfigs,
269 &ISurfaceFlingerConfigs::useVrFlinger>(false);
270
Fabien Sanglard1971b632017-03-10 14:50:03 -0800271 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
272 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
273
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600274 hasWideColorDisplay =
275 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
276
Iris Chang7501ed62018-04-30 14:45:42 +0800277 V1_1::DisplayOrientation primaryDisplayOrientation =
278 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
279 V1_1::DisplayOrientation::ORIENTATION_0);
280
281 switch (primaryDisplayOrientation) {
282 case V1_1::DisplayOrientation::ORIENTATION_90:
283 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
284 break;
285 case V1_1::DisplayOrientation::ORIENTATION_180:
286 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
287 break;
288 case V1_1::DisplayOrientation::ORIENTATION_270:
289 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
290 break;
291 default:
292 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
293 break;
294 }
295 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
296
David Sodman99974d22017-11-28 12:04:33 -0800297 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700298
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299 // debugging stuff...
300 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700301
Mathias Agopianb4b17302013-03-20 18:36:41 -0700302 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700303 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700304
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 property_get("debug.sf.showupdates", value, "0");
306 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700307
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700308 property_get("debug.sf.ddms", value, "0");
309 mDebugDDMS = atoi(value);
310 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700311 if (!startDdmConnection()) {
312 // start failed, and DDMS debugging not enabled
313 mDebugDDMS = 0;
314 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700315 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700316 ALOGI_IF(mDebugRegion, "showupdates enabled");
317 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700318
319 property_get("debug.sf.disable_backpressure", value, "0");
320 mPropagateBackpressure = !atoi(value);
321 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700322
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800323 property_get("debug.sf.enable_hwc_vds", value, "0");
324 mUseHwcVirtualDisplays = atoi(value);
325 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800326
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800327 property_get("ro.sf.disable_triple_buffer", value, "1");
328 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800329 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700330
Yiwei Zhang243b3782018-05-15 17:40:04 -0700331 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700332 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
333 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
334
Dan Stoza84d619e2018-03-28 17:07:36 -0700335 property_get("debug.sf.early_phase_offset_ns", value, "0");
336 const int earlyWakeupOffsetOffsetNs = atoi(value);
337 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
338 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
339 sfVsyncPhaseOffsetNs);
340
Romain Guy11d63f42017-07-20 12:47:14 -0700341 // We should be reading 'persist.sys.sf.color_saturation' here
342 // but since /data may be encrypted, we need to wait until after vold
343 // comes online to attempt to read the property. The property is
344 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800345
346 if (useTrebleTestingOverride()) {
347 // Without the override SurfaceFlinger cannot connect to HIDL
348 // services that are not listed in the manifests. Considered
349 // deriving the setting from the set service name, but it
350 // would be brittle if the name that's not 'default' is used
351 // for production purposes later on.
352 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354}
355
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800356void SurfaceFlinger::onFirstRef()
357{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800358 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800359}
360
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800361SurfaceFlinger::~SurfaceFlinger()
362{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800363}
364
Dan Stozac7014012014-02-14 15:03:43 -0800365void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800366{
367 // the window manager died on us. prepare its eulogy.
368
Andy McFadden13a082e2012-08-24 10:16:42 -0700369 // restore initial conditions (default device unblank, etc)
370 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800371
372 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700373 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800374}
375
Robert Carr1db73f62016-12-21 12:58:51 -0800376static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700377 status_t err = client->initCheck();
378 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800379 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380 }
Robert Carr1db73f62016-12-21 12:58:51 -0800381 return nullptr;
382}
383
384sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
385 return initClient(new Client(this));
386}
387
388sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
389 const sp<IGraphicBufferProducer>& gbp) {
390 if (authenticateSurfaceTexture(gbp) == false) {
391 return nullptr;
392 }
393 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
394 if (layer == nullptr) {
395 return nullptr;
396 }
397
398 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800399}
400
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700401sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
402 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700403{
404 class DisplayToken : public BBinder {
405 sp<SurfaceFlinger> flinger;
406 virtual ~DisplayToken() {
407 // no more references, this display must be terminated
408 Mutex::Autolock _l(flinger->mStateLock);
409 flinger->mCurrentState.displays.removeItem(this);
410 flinger->setTransactionFlags(eDisplayTransactionNeeded);
411 }
412 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700413 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700414 : flinger(flinger) {
415 }
416 };
417
418 sp<BBinder> token = new DisplayToken(this);
419
420 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700421 DisplayDeviceState info;
422 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700423 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700424 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700425 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800426 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700427 return token;
428}
429
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700430void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700431 Mutex::Autolock _l(mStateLock);
432
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700433 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700434 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700435 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700436 return;
437 }
438
439 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700440 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700441 ALOGE("destroyDisplay called for non-virtual display");
442 return;
443 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700444 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700445 mCurrentState.displays.removeItemsAt(idx);
446 setTransactionFlags(eDisplayTransactionNeeded);
447}
448
Mathias Agopiane57f2922012-08-09 16:29:12 -0700449sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700450 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700451 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800452 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700453 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700454 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700455}
456
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800457void SurfaceFlinger::bootFinished()
458{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700459 if (mStartPropertySetThread->join() != NO_ERROR) {
460 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800461 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800462 const nsecs_t now = systemTime();
463 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000464 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700465
466 // wait patiently for the window manager death
467 const String16 name("window");
468 sp<IBinder> window(defaultServiceManager()->getService(name));
469 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700470 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700471 }
472
Steven Thomas050b2c82017-03-06 11:45:16 -0800473 if (mVrFlinger) {
474 mVrFlinger->OnBootFinished();
475 }
476
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700477 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700478 // formerly we would just kill the process, but we now ask it to exit so it
479 // can choose where to stop the animation.
480 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700481
482 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
483 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
484 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700485
Dominik Laskowski8c001672018-05-30 16:52:06 -0700486 postMessageAsync(new LambdaMessage([this] { readPersistentProperties(); }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800487}
488
Mathias Agopian3f844832013-08-07 21:24:32 -0700489void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700490 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700491}
492
Lloyd Piquee83f9312018-02-01 12:53:17 -0800493class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700494public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700495 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000496 const char* name) :
497 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700498 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700499 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000500 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
501 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700502 mDispSync(dispSync),
503 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700504 mVsyncMutex(),
505 mPhaseOffset(phaseOffset),
506 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700507
Lloyd Piquee83f9312018-02-01 12:53:17 -0800508 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700509
Lloyd Piquee83f9312018-02-01 12:53:17 -0800510 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700511 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000513 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700514 static_cast<DispSync::Callback*>(this));
515 if (err != NO_ERROR) {
516 ALOGE("error registering vsync callback: %s (%d)",
517 strerror(-err), err);
518 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700519 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700520 } else {
521 status_t err = mDispSync->removeEventListener(
522 static_cast<DispSync::Callback*>(this));
523 if (err != NO_ERROR) {
524 ALOGE("error unregistering vsync callback: %s (%d)",
525 strerror(-err), err);
526 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700527 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700528 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700529 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530 }
531
Lloyd Piquee83f9312018-02-01 12:53:17 -0800532 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534 mCallback = callback;
535 }
536
Lloyd Piquee83f9312018-02-01 12:53:17 -0800537 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700538 Mutex::Autolock lock(mVsyncMutex);
539
540 // Normalize phaseOffset to [0, period)
541 auto period = mDispSync->getPeriod();
542 phaseOffset %= period;
543 if (phaseOffset < 0) {
544 // If we're here, then phaseOffset is in (-period, 0). After this
545 // operation, it will be in (0, period)
546 phaseOffset += period;
547 }
548 mPhaseOffset = phaseOffset;
549
550 // If we're not enabled, we don't need to mess with the listeners
551 if (!mEnabled) {
552 return;
553 }
554
Dan Stoza84d619e2018-03-28 17:07:36 -0700555 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
556 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700557 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700558 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700559 strerror(-err), err);
560 }
561 }
562
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700563private:
564 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800565 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700566 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700567 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568 callback = mCallback;
569
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700570 if (mTraceVsync) {
571 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700572 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700573 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574 }
575
Peiyong Lin566a3b42018-01-09 18:22:43 -0800576 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577 callback->onVSyncEvent(when);
578 }
579 }
580
Tim Murray4a4e4a22016-04-19 16:29:23 +0000581 const char* const mName;
582
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700583 int mValue;
584
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700585 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700586 const String8 mVsyncOnLabel;
587 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700588
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700590
591 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800592 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700593
594 Mutex mVsyncMutex; // Protects the following
595 nsecs_t mPhaseOffset;
596 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700597};
598
Lloyd Piquee83f9312018-02-01 12:53:17 -0800599class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700600public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800601 InjectVSyncSource() = default;
602 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700603
Lloyd Piquee83f9312018-02-01 12:53:17 -0800604 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700605 std::lock_guard<std::mutex> lock(mCallbackMutex);
606 mCallback = callback;
607 }
608
Lloyd Piquee83f9312018-02-01 12:53:17 -0800609 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700610 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700611 if (mCallback) {
612 mCallback->onVSyncEvent(when);
613 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700614 }
615
Lloyd Piquee83f9312018-02-01 12:53:17 -0800616 void setVSyncEnabled(bool) override {}
617 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700618
619private:
620 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800621 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700622};
623
Wei Wangf9b05ee2017-07-19 20:59:39 -0700624// Do not call property_set on main thread which will be blocked by init
625// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700626void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700627 ALOGI( "SurfaceFlinger's main thread ready to run. "
628 "Initializing graphics H/W...");
629
Thierry Strudel2924d012017-08-14 15:19:37 -0700630 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900631
Steven Thomasb02664d2017-07-26 18:48:28 -0700632 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800633
Steven Thomasb02664d2017-07-26 18:48:28 -0700634 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800635 mEventThreadSource =
636 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
637 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800638 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700639 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800640 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800641 "appEventThread");
642 mSfEventThreadSource =
643 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
644 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800645
Lloyd Pique24b0a482018-03-09 18:52:26 -0800646 mSFEventThread =
647 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700648 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800649 [this](nsecs_t timestamp) {
650 mInterceptor->saveVSyncEvent(timestamp);
651 },
652 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800653 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza84d619e2018-03-28 17:07:36 -0700654 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800655
Steven Thomasb02664d2017-07-26 18:48:28 -0700656 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800657 getBE().mRenderEngine =
658 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
659 hasWideColorDisplay
660 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
661 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800662 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700663
664 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
665 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800666 getBE().mHwc.reset(
667 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700668 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800669 // Process any initial hotplug and resulting display changes.
670 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700671 const auto display = getDefaultDisplayDeviceLocked();
672 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
673 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
674 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800675
Lloyd Piquefcd86612017-12-14 17:15:36 -0800676 // make the default display GLContext current so that we can create textures
677 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700678 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800679
Steven Thomas050b2c82017-03-06 11:45:16 -0800680 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700681 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700682 // This callback is called from the vr flinger dispatch thread. We
683 // need to call signalTransaction(), which requires holding
684 // mStateLock when we're not on the main thread. Acquiring
685 // mStateLock from the vr flinger dispatch thread might trigger a
686 // deadlock in surface flinger (see b/66916578), so post a message
687 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700688 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700689 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
690 mVrFlingerRequestsDisplay = requestDisplay;
691 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700692 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800693 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700694 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
695 getHwComposer()
696 .getHwcDisplayId(display->getId())
697 .value_or(0),
698 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800699 if (!mVrFlinger) {
700 ALOGE("Failed to start vrflinger");
701 }
702 }
703
Lloyd Pique379adc12018-01-22 17:31:47 -0800704 mEventControlThread = std::make_unique<impl::EventControlThread>(
705 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700706
Mathias Agopian92a979a2012-08-02 18:32:23 -0700707 // initialize our drawing state
708 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700709
Andy McFadden13a082e2012-08-24 10:16:42 -0700710 // set initial conditions (e.g. unblank default device)
711 initializeDisplays();
712
David Sodmanbc815282017-11-05 18:57:52 -0800713 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700714
Wei Wangf9b05ee2017-07-19 20:59:39 -0700715 // Inform native graphics APIs whether the present timestamp is supported:
716 if (getHwComposer().hasCapability(
717 HWC2::Capability::PresentFenceIsNotReliable)) {
718 mStartPropertySetThread = new StartPropertySetThread(false);
719 } else {
720 mStartPropertySetThread = new StartPropertySetThread(true);
721 }
722
723 if (mStartPropertySetThread->Start() != NO_ERROR) {
724 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800725 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800726
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700727 mLegacySrgbSaturationMatrix =
728 getHwComposer().getDataspaceSaturationMatrix(display->getId(), Dataspace::SRGB_LINEAR);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800729
Dan Stoza9e56aa02015-11-02 13:00:03 -0800730 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700731}
732
Romain Guy11d63f42017-07-20 12:47:14 -0700733void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700734 Mutex::Autolock _l(mStateLock);
735
Romain Guy11d63f42017-07-20 12:47:14 -0700736 char value[PROPERTY_VALUE_MAX];
737
738 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800739 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700740 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800741 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100742
743 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700744 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700745}
746
Mathias Agopiana67e4182012-06-19 17:26:12 -0700747void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800748 // Start boot animation service by setting a property mailbox
749 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700750 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800751 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700752 if (mStartPropertySetThread->join() != NO_ERROR) {
753 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800754 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700755}
756
Mathias Agopian875d8e12013-06-07 15:35:48 -0700757size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800758 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700759}
760
Mathias Agopian875d8e12013-06-07 15:35:48 -0700761size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800762 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700763}
764
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800765// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800766
Jamie Gennis582270d2011-08-17 18:19:00 -0700767bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800768 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800769 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800770 return authenticateSurfaceTextureLocked(bufferProducer);
771}
772
773bool SurfaceFlinger::authenticateSurfaceTextureLocked(
774 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800775 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800776 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800777}
778
Brian Anderson6b376712017-04-04 10:51:39 -0700779status_t SurfaceFlinger::getSupportedFrameTimestamps(
780 std::vector<FrameEvent>* outSupported) const {
781 *outSupported = {
782 FrameEvent::REQUESTED_PRESENT,
783 FrameEvent::ACQUIRE,
784 FrameEvent::LATCH,
785 FrameEvent::FIRST_REFRESH_START,
786 FrameEvent::LAST_REFRESH_START,
787 FrameEvent::GPU_COMPOSITION_DONE,
788 FrameEvent::DEQUEUE_READY,
789 FrameEvent::RELEASE,
790 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700791 ConditionalLock _l(mStateLock,
792 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700793 if (!getHwComposer().hasCapability(
794 HWC2::Capability::PresentFenceIsNotReliable)) {
795 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
796 }
797 return NO_ERROR;
798}
799
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700800status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
801 Vector<DisplayInfo>* configs) {
802 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700803 return BAD_VALUE;
804 }
805
Jesse Hall692c7232012-11-08 15:41:56 -0800806 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700807 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
808 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700809 type = i;
810 break;
811 }
812 }
813
814 if (type < 0) {
815 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700816 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 // TODO: Not sure if display density should handled by SF any longer
819 class Density {
820 static int getDensityFromProperty(char const* propName) {
821 char property[PROPERTY_VALUE_MAX];
822 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800823 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 density = atoi(property);
825 }
826 return density;
827 }
828 public:
829 static int getEmuDensity() {
830 return getDensityFromProperty("qemu.sf.lcd_density"); }
831 static int getBuildDensity() {
832 return getDensityFromProperty("ro.sf.lcd_density"); }
833 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700834
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700836
Steven Thomas6d8110b2017-08-31 18:24:21 -0700837 ConditionalLock _l(mStateLock,
838 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800839 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700840 DisplayInfo info = DisplayInfo();
841
Dan Stoza9e56aa02015-11-02 13:00:03 -0800842 float xdpi = hwConfig->getDpiX();
843 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700844
845 if (type == DisplayDevice::DISPLAY_PRIMARY) {
846 // The density of the device is provided by a build property
847 float density = Density::getBuildDensity() / 160.0f;
848 if (density == 0) {
849 // the build doesn't provide a density -- this is wrong!
850 // use xdpi instead
851 ALOGE("ro.sf.lcd_density must be defined as a build property");
852 density = xdpi / 160.0f;
853 }
854 if (Density::getEmuDensity()) {
855 // if "qemu.sf.lcd_density" is specified, it overrides everything
856 xdpi = ydpi = density = Density::getEmuDensity();
857 density /= 160.0f;
858 }
859 info.density = density;
860
861 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700862 const auto display = getDefaultDisplayDeviceLocked();
863 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 } else {
865 // TODO: where should this value come from?
866 static const int TV_DENSITY = 213;
867 info.density = TV_DENSITY / 160.0f;
868 info.orientation = 0;
869 }
870
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871 info.w = hwConfig->getWidth();
872 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700873 info.xdpi = xdpi;
874 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800875 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900876 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800877
Andy McFadden91b2ca82014-06-13 14:04:23 -0700878 // This is how far in advance a buffer must be queued for
879 // presentation at a given time. If you want a buffer to appear
880 // on the screen at time N, you must submit the buffer before
881 // (N - presentationDeadline).
882 //
883 // Normally it's one full refresh period (to give SF a chance to
884 // latch the buffer), but this can be reduced by configuring a
885 // DispSync offset. Any additional delays introduced by the hardware
886 // composer or panel must be accounted for here.
887 //
888 // We add an additional 1ms to allow for processing time and
889 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800891 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700892
893 // All non-virtual displays are currently considered secure.
894 info.secure = true;
895
Iris Chang7501ed62018-04-30 14:45:42 +0800896 if (type == DisplayDevice::DISPLAY_PRIMARY &&
897 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
898 std::swap(info.w, info.h);
899 }
900
Michael Wright28f24d02016-07-12 13:30:53 -0700901 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700902 }
903
Dan Stoza7f7da322014-05-02 15:26:25 -0700904 return NO_ERROR;
905}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700906
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700907status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
908 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700909 return BAD_VALUE;
910 }
911
912 // FIXME for now we always return stats for the primary display
913 memset(stats, 0, sizeof(*stats));
914 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
915 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
916 return NO_ERROR;
917}
918
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700919int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
920 const auto display = getDisplayDevice(displayToken);
921 if (!display) {
922 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800923 return BAD_VALUE;
924 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700925
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700926 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700927}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700928
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700929void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
930 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700931 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700932 return;
933 }
934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700936 ALOGW("Trying to set config for virtual display");
937 return;
938 }
939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940 display->setActiveConfig(mode);
941 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700942}
943
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700944status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700945 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700946 Vector<DisplayInfo> configs;
947 getDisplayConfigs(displayToken, &configs);
948 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
949 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
950 configs.size());
951 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700952 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700953 const auto display = getDisplayDevice(displayToken);
954 if (!display) {
955 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
956 displayToken.get());
957 } else if (display->isVirtual()) {
958 ALOGW("Attempt to set active config %d for virtual display", mode);
959 } else {
960 setActiveConfigInternal(display, mode);
961 }
962 }));
963
Mathias Agopian888c8222012-08-04 21:10:38 -0700964 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700965}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700966status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
967 Vector<ColorMode>* outColorModes) {
968 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700969 return BAD_VALUE;
970 }
971
Michael Wright28f24d02016-07-12 13:30:53 -0700972 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700973 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
974 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700975 type = i;
976 break;
977 }
978 }
979
980 if (type < 0) {
981 return type;
982 }
983
Peiyong Lina52f0292018-03-14 17:26:31 -0700984 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700985 {
986 ConditionalLock _l(mStateLock,
987 std::this_thread::get_id() != mMainThreadId);
988 modes = getHwComposer().getColorModes(type);
989 }
Michael Wright28f24d02016-07-12 13:30:53 -0700990 outColorModes->clear();
991 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
992
993 return NO_ERROR;
994}
995
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700996ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
997 if (const auto display = getDisplayDevice(displayToken)) {
998 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700999 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001000 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001001}
1002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001003void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1004 Dataspace dataSpace, RenderIntent renderIntent) {
1005 ColorMode currentMode = display->getActiveColorMode();
1006 Dataspace currentDataSpace = display->getCompositionDataSpace();
1007 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001008
Peiyong Lin38e9a562018-04-10 16:24:20 -07001009 if (mode == currentMode && dataSpace == currentDataSpace &&
1010 renderIntent == currentRenderIntent) {
1011 return;
1012 }
1013
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001014 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001015 ALOGW("Trying to set config for virtual display");
1016 return;
1017 }
1018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001019 display->setActiveColorMode(mode);
1020 display->setCompositionDataSpace(dataSpace);
1021 display->setActiveRenderIntent(renderIntent);
1022 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001023
1024 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1026 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001027}
1028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001030 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031 Vector<ColorMode> modes;
1032 getDisplayColorModes(displayToken, &modes);
1033 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1034 if (mode < ColorMode::NATIVE || !exists) {
1035 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1036 decodeColorMode(mode).c_str(), mode, displayToken.get());
1037 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001038 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001039 const auto display = getDisplayDevice(displayToken);
1040 if (!display) {
1041 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1042 decodeColorMode(mode).c_str(), mode, displayToken.get());
1043 } else if (display->isVirtual()) {
1044 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1045 decodeColorMode(mode).c_str(), mode);
1046 } else {
1047 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1048 RenderIntent::COLORIMETRIC);
1049 }
1050 }));
1051
Michael Wright28f24d02016-07-12 13:30:53 -07001052 return NO_ERROR;
1053}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001054
Svetoslavd85084b2014-03-20 10:28:31 -07001055status_t SurfaceFlinger::clearAnimationFrameStats() {
1056 Mutex::Autolock _l(mStateLock);
1057 mAnimFrameTracker.clearStats();
1058 return NO_ERROR;
1059}
1060
1061status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1062 Mutex::Autolock _l(mStateLock);
1063 mAnimFrameTracker.getStats(outStats);
1064 return NO_ERROR;
1065}
1066
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001067status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1068 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001069 Mutex::Autolock _l(mStateLock);
1070
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001071 const auto display = getDisplayDeviceLocked(displayToken);
1072 if (!display) {
1073 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001074 return BAD_VALUE;
1075 }
1076
Peiyong Linfb069302018-04-25 14:34:31 -07001077 // At this point the DisplayDeivce should already be set up,
1078 // meaning the luminance information is already queried from
1079 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001081 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1082 capabilities.getDesiredMaxLuminance(),
1083 capabilities.getDesiredMaxAverageLuminance(),
1084 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001085
1086 return NO_ERROR;
1087}
1088
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001089status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001090 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001091 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001092
Chia-I Wu90f669f2017-10-05 14:24:41 -07001093 if (mInjectVSyncs == enable) {
1094 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001095 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096
1097 if (enable) {
1098 ALOGV("VSync Injections enabled");
1099 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001100 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001101 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001102 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001103 impl::EventThread::InterceptVSyncsCallback(),
1104 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001105 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001106 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001107 } else {
1108 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001109 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001110 }
1111
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001112 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001113 }));
1114
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001115 return NO_ERROR;
1116}
1117
1118status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001119 Mutex::Autolock _l(mStateLock);
1120
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001121 if (!mInjectVSyncs) {
1122 ALOGE("VSync Injections not enabled");
1123 return BAD_VALUE;
1124 }
1125 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1126 ALOGV("Injecting VSync inside SurfaceFlinger");
1127 mVSyncInjector->onInjectSyncEvent(when);
1128 }
1129 return NO_ERROR;
1130}
1131
Lloyd Pique755e3192018-01-31 16:46:15 -08001132status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1133 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001134 IPCThreadState* ipc = IPCThreadState::self();
1135 const int pid = ipc->getCallingPid();
1136 const int uid = ipc->getCallingUid();
1137 if ((uid != AID_SHELL) &&
1138 !PermissionCache::checkPermission(sDump, pid, uid)) {
1139 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1140 return PERMISSION_DENIED;
1141 }
1142
1143 // Try to acquire a lock for 1s, fail gracefully
1144 const status_t err = mStateLock.timedLock(s2ns(1));
1145 const bool locked = (err == NO_ERROR);
1146 if (!locked) {
1147 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1148 return TIMED_OUT;
1149 }
1150
1151 outLayers->clear();
1152 mCurrentState.traverseInZOrder([&](Layer* layer) {
1153 outLayers->push_back(layer->getLayerDebugInfo());
1154 });
1155
1156 mStateLock.unlock();
1157 return NO_ERROR;
1158}
1159
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001160// ----------------------------------------------------------------------------
1161
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001162sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1163 ISurfaceComposer::VsyncSource vsyncSource) {
1164 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1165 return mSFEventThread->createEventConnection();
1166 } else {
1167 return mEventThread->createEventConnection();
1168 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001169}
1170
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001171// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001172
1173void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001174 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001175}
1176
1177void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001178 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001179}
1180
1181void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001182 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001183}
1184
1185void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001186 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001187 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001188}
1189
1190status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001191 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001192 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001193}
1194
1195status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001196 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001197 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001198 if (res == NO_ERROR) {
1199 msg->wait();
1200 }
1201 return res;
1202}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001203
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001204void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001205 do {
1206 waitForEvent();
1207 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001208}
1209
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001210void SurfaceFlinger::enableHardwareVsync() {
1211 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001212 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001213 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001214 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001215 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001216 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001217}
1218
Jesse Hall948fe0c2013-10-14 12:56:09 -07001219void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001220 Mutex::Autolock _l(mHWVsyncLock);
1221
Jesse Hall948fe0c2013-10-14 12:56:09 -07001222 if (makeAvailable) {
1223 mHWVsyncAvailable = true;
1224 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001225 // Hardware vsync is not currently available, so abort the resync
1226 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001227 return;
1228 }
1229
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001230 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1231 if (!getHwComposer().isConnected(displayId)) {
1232 return;
1233 }
1234
1235 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001236 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001237
1238 mPrimaryDispSync.reset();
1239 mPrimaryDispSync.setPeriod(period);
1240
1241 if (!mPrimaryHWVsyncEnabled) {
1242 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001243 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001244 mPrimaryHWVsyncEnabled = true;
1245 }
1246}
1247
Jesse Hall948fe0c2013-10-14 12:56:09 -07001248void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001249 Mutex::Autolock _l(mHWVsyncLock);
1250 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001251 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001252 mPrimaryDispSync.endResync();
1253 mPrimaryHWVsyncEnabled = false;
1254 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001255 if (makeUnavailable) {
1256 mHWVsyncAvailable = false;
1257 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001258}
1259
Tim Murray4a4e4a22016-04-19 16:29:23 +00001260void SurfaceFlinger::resyncWithRateLimit() {
1261 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001262
1263 // No explicit locking is needed here since EventThread holds a lock while calling this method
1264 static nsecs_t sLastResyncAttempted = 0;
1265 const nsecs_t now = systemTime();
1266 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001267 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001268 }
Dan Stoza57164302017-05-08 14:03:54 -07001269 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001270}
1271
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001272void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1273 int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001274 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001275 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001276 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001277 return;
1278 }
1279
1280 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001281 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001282 return;
1283 }
1284
Jamie Gennisd1700752013-10-14 12:22:52 -07001285 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001286
Jamie Gennisd1700752013-10-14 12:22:52 -07001287 { // Scope for the lock
1288 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001289 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001290 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001291 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001292 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001293
1294 if (needsHwVsync) {
1295 enableHardwareVsync();
1296 } else {
1297 disableHardwareVsync(false);
1298 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001299}
1300
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001301void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001302 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1303 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001304}
1305
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001306void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001307 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001308 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001309 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001310
Lloyd Piqueba04e622017-12-14 17:11:26 -08001311 // Ignore events that do not have the right sequenceId.
1312 if (sequenceId != getBE().mComposerSequenceId) {
1313 return;
1314 }
1315
Steven Thomasb02664d2017-07-26 18:48:28 -07001316 // Only lock if we're not on the main thread. This function is normally
1317 // called on a hwbinder thread, but for the primary display it's called on
1318 // the main thread with the state lock already held, so don't attempt to
1319 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001320 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001321
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001322 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001323
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001324 if (std::this_thread::get_id() == mMainThreadId) {
1325 // Process all pending hot plug events immediately if we are on the main thread.
1326 processDisplayHotplugEventsLocked();
1327 }
1328
Lloyd Piqueba04e622017-12-14 17:11:26 -08001329 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001330}
1331
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001332void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001333 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001334 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001335 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001336 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001337 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001338}
1339
Dan Stoza9e56aa02015-11-02 13:00:03 -08001340void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001341 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001342 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001343 getHwComposer().setVsyncEnabled(disp,
1344 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001345}
1346
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001347// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001348void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001349 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001350 // Clear the drawing state so that the logic inside of
1351 // handleTransactionLocked will fire. It will determine the delta between
1352 // mCurrentState and mDrawingState and re-apply all changes when we make the
1353 // transition.
1354 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001355 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001356 mDisplays.clear();
1357}
1358
Steven Thomas050b2c82017-03-06 11:45:16 -08001359void SurfaceFlinger::updateVrFlinger() {
1360 if (!mVrFlinger)
1361 return;
1362 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001363 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001364 return;
1365 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001366
David Sodman105b7dc2017-11-04 20:28:14 -07001367 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001368 ALOGE("Vr flinger is only supported for remote hardware composer"
1369 " service connections. Ignoring request to transition to vr"
1370 " flinger.");
1371 mVrFlingerRequestsDisplay = false;
1372 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001373 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001374
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001375 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001376
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001377 const auto display = getDefaultDisplayDeviceLocked();
1378 LOG_ALWAYS_FATAL_IF(!display);
1379 const int currentDisplayPowerMode = display->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001380
Steven Thomasb02664d2017-07-26 18:48:28 -07001381 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001382 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001384
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001386 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001387 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1388 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001389 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001390
David Sodman105b7dc2017-11-04 20:28:14 -07001391 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1392 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001393
1394 if (vrFlingerRequestsDisplay) {
1395 mVrFlinger->GrantDisplayOwnership();
1396 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001397 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001398 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001399
1400 mVisibleRegionsDirty = true;
1401 invalidateHwcGeometry();
1402
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001403 // Re-enable default display.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001404 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001405
Steven Thomasb02664d2017-07-26 18:48:28 -07001406 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001407 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001408 const nsecs_t period = activeConfig->getVsyncPeriod();
1409 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001410
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 // Use phase of 0 since phase is not known.
1412 // Use latency of 0, which will snap to the ideal latency.
1413 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001414
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001415 android_atomic_or(1, &mRepaintEverything);
1416 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001417}
1418
Mathias Agopian4fec8732012-06-29 14:12:52 -07001419void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001420 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001421 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001422 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001423 bool frameMissed = !mHadClientComposition &&
1424 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001425 (mPreviousPresentFence->getSignalTime() ==
1426 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001427 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001428 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001429 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001430 mTimeStats.incrementMissedFrames();
1431 if (mPropagateBackpressure) {
1432 signalLayerUpdate();
1433 break;
1434 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001435 }
Dan Stoza50182882016-07-08 12:02:20 -07001436
Steven Thomas050b2c82017-03-06 11:45:16 -08001437 // Now that we're going to make it to the handleMessageTransaction()
1438 // call below it's safe to call updateVrFlinger(), which will
1439 // potentially trigger a display handoff.
1440 updateVrFlinger();
1441
Dan Stoza6b9454d2014-11-07 16:00:59 -08001442 bool refreshNeeded = handleMessageTransaction();
1443 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001444 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001445 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001446 // Signal a refresh if a transaction modified the window state,
1447 // a new buffer was latched, or if HWC has requested a full
1448 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001449 signalRefresh();
1450 }
1451 break;
1452 }
1453 case MessageQueue::REFRESH: {
1454 handleMessageRefresh();
1455 break;
1456 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001457 }
1458}
1459
Dan Stoza6b9454d2014-11-07 16:00:59 -08001460bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001461 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001462 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001463 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001464 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001465 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001466 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001467}
1468
Dan Stoza6b9454d2014-11-07 16:00:59 -08001469bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001470 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001471 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001472}
1473
1474void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001475 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001476
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001477 mRefreshPending = false;
1478
Chia-I Wu30505fb2018-03-26 16:20:31 -07001479 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001480
Chia-I Wu30505fb2018-03-26 16:20:31 -07001481 preComposition(refreshStartTime);
1482 rebuildLayerStacks();
1483 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001484 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001485 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001486 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001487 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001488 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001489
Dan Stozabfbffeb2016-07-21 14:49:33 -07001490 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001491 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001492 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001493 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001494 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001495 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001496
Dan Stoza9e56aa02015-11-02 13:00:03 -08001497 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001498}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001499
Mathias Agopiancd60f992012-08-16 16:28:27 -07001500void SurfaceFlinger::doDebugFlashRegions()
1501{
1502 // is debugging enabled
1503 if (CC_LIKELY(!mDebugRegion))
1504 return;
1505
1506 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001507 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001508 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001509 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001510 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001511 if (!dirtyRegion.isEmpty()) {
1512 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001513 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001514
1515 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001516 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001517 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001518 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1519
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001520 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001521 }
1522 }
1523 }
1524
1525 postFramebuffer();
1526
1527 if (mDebugRegion > 1) {
1528 usleep(mDebugRegion * 1000);
1529 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001530
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001531 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001532 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001533 continue;
1534 }
1535
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001536 status_t result = display->prepareFrame(*getBE().mHwc);
1537 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001538 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001539 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001540}
1541
Adrian Roos1e1a1282017-11-01 19:05:31 +01001542void SurfaceFlinger::doTracing(const char* where) {
1543 ATRACE_CALL();
1544 ATRACE_NAME(where);
1545 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001546 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001547 }
1548}
1549
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001550void SurfaceFlinger::logLayerStats() {
1551 ATRACE_CALL();
1552 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001553 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001554 if (display->isPrimary()) {
1555 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001556 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001557 }
1558 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001559
1560 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001561 }
1562}
1563
Chia-I Wu30505fb2018-03-26 16:20:31 -07001564void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001565{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001566 ATRACE_CALL();
1567 ALOGV("preComposition");
1568
Mathias Agopiancd60f992012-08-16 16:28:27 -07001569 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001570 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001571 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001572 needExtraInvalidate = true;
1573 }
Robert Carr2047fae2016-11-28 14:09:09 -08001574 });
1575
Mathias Agopiancd60f992012-08-16 16:28:27 -07001576 if (needExtraInvalidate) {
1577 signalLayerUpdate();
1578 }
1579}
1580
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001581void SurfaceFlinger::updateCompositorTiming(
1582 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1583 std::shared_ptr<FenceTime>& presentFenceTime) {
1584 // Update queue of past composite+present times and determine the
1585 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001586 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001587 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001588 while (!getBE().mCompositePresentTimes.empty()) {
1589 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001590 // Cached values should have been updated before calling this method,
1591 // which helps avoid duplicate syscalls.
1592 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1593 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1594 break;
1595 }
1596 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001597 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001598 }
1599
1600 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001601 while (getBE().mCompositePresentTimes.size() > 16) {
1602 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001603 }
1604
Brian Andersond0010582017-03-07 13:20:31 -08001605 setCompositorTimingSnapped(
1606 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1607}
1608
1609void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1610 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001611 // Integer division and modulo round toward 0 not -inf, so we need to
1612 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001613 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001614 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1615 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1616
Brian Andersond0010582017-03-07 13:20:31 -08001617 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1618 if (idealLatency <= 0) {
1619 idealLatency = vsyncInterval;
1620 }
1621
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001622 // Snap the latency to a value that removes scheduling jitter from the
1623 // composition and present times, which often have >1ms of jitter.
1624 // Reducing jitter is important if an app attempts to extrapolate
1625 // something (such as user input) to an accurate diasplay time.
1626 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1627 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001628 nsecs_t bias = vsyncInterval / 2;
1629 int64_t extraVsyncs =
1630 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1631 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1632 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001633
David Sodman99974d22017-11-28 12:04:33 -08001634 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1635 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1636 getBE().mCompositorTiming.interval = vsyncInterval;
1637 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001638}
1639
Chia-I Wu30505fb2018-03-26 16:20:31 -07001640void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001641{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001642 ATRACE_CALL();
1643 ALOGV("postComposition");
1644
Brian Anderson3546a3f2016-07-14 11:51:14 -07001645 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001646 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001647 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001648 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001649 }
1650
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001651 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001652 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001653
David Sodman73beded2017-11-15 11:56:06 -08001654 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001655 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001656 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001657 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001658 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001659 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001660 } else {
1661 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1662 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001663
David Sodman73beded2017-11-15 11:56:06 -08001664 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001665 mPreviousPresentFence =
1666 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1667 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001668 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001669
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001670 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1671 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1672
Chia-I Wu30505fb2018-03-26 16:20:31 -07001673 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001674 // when we started doing work for this frame, but that should be okay
1675 // since updateCompositorTiming has snapping logic.
1676 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001677 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001678 CompositorTiming compositorTiming;
1679 {
David Sodman99974d22017-11-28 12:04:33 -08001680 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1681 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001682 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001683
Robert Carr2047fae2016-11-28 14:09:09 -08001684 mDrawingState.traverseInZOrder([&](Layer* layer) {
1685 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001686 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001687 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001688 recordBufferingStats(layer->getName().string(),
1689 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001690 }
Robert Carr2047fae2016-11-28 14:09:09 -08001691 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001692
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001693 if (presentFenceTime->isValid()) {
1694 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001695 enableHardwareVsync();
1696 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001697 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001698 }
1699 }
1700
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001701 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001702 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001703 enableHardwareVsync();
1704 }
1705 }
1706
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001707 if (mAnimCompositionPending) {
1708 mAnimCompositionPending = false;
1709
Brian Anderson4e606e32017-03-16 15:34:57 -07001710 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001711 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001712 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001713 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001714 // The HWC doesn't support present fences, so use the refresh
1715 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001716 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001717 mAnimFrameTracker.setActualPresentTime(presentTime);
1718 }
1719 mAnimFrameTracker.advanceFrame();
1720 }
Dan Stozab90cf072015-03-05 11:05:59 -08001721
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001722 mTimeStats.incrementTotalFrames();
1723 if (mHadClientComposition) {
1724 mTimeStats.incrementClientCompositionFrames();
1725 }
1726
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001727 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001728 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001729 return;
1730 }
1731
1732 nsecs_t currentTime = systemTime();
1733 if (mHasPoweredOff) {
1734 mHasPoweredOff = false;
1735 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001736 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001737 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001738 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1739 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001740 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001741 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001742 }
David Sodman4a36e932017-11-07 14:29:47 -08001743 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001744 }
David Sodman4a36e932017-11-07 14:29:47 -08001745 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001746}
1747
1748void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001749 ATRACE_CALL();
1750 ALOGV("rebuildLayerStacks");
1751
Mathias Agopiancd60f992012-08-16 16:28:27 -07001752 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001753 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001754 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001755 mVisibleRegionsDirty = false;
1756 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001757
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001758 for (const auto& pair : mDisplays) {
1759 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001760 Region opaqueRegion;
1761 Region dirtyRegion;
1762 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001763 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001764 const Transform& tr = display->getTransform();
1765 const Rect bounds = display->getBounds();
1766 if (display->isPoweredOn()) {
1767 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001768
Jeff Sharkey76488112017-02-27 14:15:18 -07001769 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001770 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001771 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001772 Region drawRegion(tr.transform(
1773 layer->visibleNonTransparentRegion));
1774 drawRegion.andSelf(bounds);
1775 if (!drawRegion.isEmpty()) {
1776 layersSortedByZ.add(layer);
1777 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001778 // Clear out the HWC layer if this layer was
1779 // previously visible, but no longer is
Dominik Laskowski7e045462018-05-30 13:02:02 -07001780 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001781 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001782 } else {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001783 // WM changes display->layerStack upon sleep/awake.
Chia-I Wu30505fb2018-03-26 16:20:31 -07001784 // Here we make sure we delete the HWC layers even if
1785 // WM changed their layer stack.
Dominik Laskowski7e045462018-05-30 13:02:02 -07001786 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001787 }
1788
1789 // If a layer is not going to get a release fence because
1790 // it is invisible, but it is also going to release its
1791 // old buffer, add it to the list of layers needing
1792 // fences.
1793 if (hwcLayerDestroyed) {
1794 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1795 mLayersWithQueuedFrames.cend(), layer);
1796 if (found != mLayersWithQueuedFrames.cend()) {
1797 layersNeedingFences.add(layer);
1798 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001799 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001800 });
1801 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001802 display->setVisibleLayersSortedByZ(layersSortedByZ);
1803 display->setLayersNeedingFences(layersNeedingFences);
1804 display->undefinedRegion.set(bounds);
1805 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1806 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001807 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001808 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001809}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001810
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001811// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001812// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001813// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001814// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001815// The returned HDR data space is one of
1816// - Dataspace::UNKNOWN
1817// - Dataspace::BT2020_HLG
1818// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001819Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1820 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001821 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001822 *outHdrDataSpace = Dataspace::UNKNOWN;
1823
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001824 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001825 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001826 case Dataspace::V0_SCRGB:
1827 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001828 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001829 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001830 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001831 case Dataspace::BT2020_PQ:
1832 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001833 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001834 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001835 case Dataspace::BT2020_HLG:
1836 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001837 // When there's mixed PQ content and HLG content, we set the HDR
1838 // data space to be BT2020_PQ and convert HLG to PQ.
1839 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1840 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001841 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001842 break;
1843 default:
1844 break;
1845 }
Romain Guy54f154a2017-10-24 21:40:32 +01001846 }
1847
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001848 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001849}
1850
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001851// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001852void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1853 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001854 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1855 *outMode = ColorMode::NATIVE;
1856 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001857 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001858 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001859 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001860
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001861 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001862 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001863
Peiyong Lindfde5112018-06-05 10:58:41 -07001864 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001865 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001866 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001867 if (isHdr) {
1868 bestDataSpace = hdrDataSpace;
1869 }
1870
Chia-I Wu0d711262018-05-21 15:19:35 -07001871 RenderIntent intent;
1872 switch (mDisplayColorSetting) {
1873 case DisplayColorSetting::MANAGED:
1874 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001875 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001876 break;
1877 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001878 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001879 break;
1880 default: // vendor display color setting
1881 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1882 break;
1883 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001884
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001885 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001886}
1887
Chia-I Wu30505fb2018-03-26 16:20:31 -07001888void SurfaceFlinger::setUpHWComposer() {
1889 ATRACE_CALL();
1890 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001892 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001893 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
1894 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1895 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07001896
1897 // If nothing has changed (!dirty), don't recompose.
1898 // If something changed, but we don't currently have any visible layers,
1899 // and didn't when we last did a composition, then skip it this time.
1900 // The second rule does two things:
1901 // - When all layers are removed from a display, we'll emit one black
1902 // frame, then nothing more until we get new layers.
1903 // - When a display is created with a private layer stack, we won't
1904 // emit any black frames until a layer is added to the layer stack.
1905 bool mustRecompose = dirty && !(empty && wasEmpty);
1906
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001907 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001908 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
1909 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07001910
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001911 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001912
1913 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001914 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07001915 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001916 }
1917
Chia-I Wu30505fb2018-03-26 16:20:31 -07001918 // build the h/w work list
1919 if (CC_UNLIKELY(mGeometryInvalid)) {
1920 mGeometryInvalid = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001921 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001922 const auto displayId = display->getId();
1923 if (displayId >= 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001924 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001925 for (size_t i = 0; i < currentLayers.size(); i++) {
1926 const auto& layer = currentLayers[i];
Dominik Laskowski7e045462018-05-30 13:02:02 -07001927 if (!layer->hasHwcLayer(displayId)) {
1928 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1929 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001930 continue;
1931 }
1932 }
1933
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001934 layer->setGeometry(display, i);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001935 if (mDebugDisableHWC || mDebugRegion) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001936 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001937 }
1938 }
1939 }
1940 }
1941 }
1942
Chia-I Wu30505fb2018-03-26 16:20:31 -07001943 // Set the per-frame data
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001944 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001945 const auto displayId = display->getId();
1946 if (displayId < 0) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001947 continue;
1948 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07001949
Chia-I Wu28f320b2018-05-03 11:02:56 -07001950 if (mDrawingState.colorMatrixChanged) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001951 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski7e045462018-05-30 13:02:02 -07001952 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001953 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001954 displayId, result);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001955 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001956 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu692e0832018-06-05 15:46:58 -07001957 if (layer->isHdrY410()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001958 layer->forceClientComposition(displayId);
Chia-I Wu692e0832018-06-05 15:46:58 -07001959 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1960 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1961 !display->hasHDR10Support()) {
1962 layer->forceClientComposition(displayId);
1963 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1964 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1965 !display->hasHLGSupport()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001966 layer->forceClientComposition(displayId);
Peiyong Linf59a7192018-04-25 11:19:31 -07001967 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001968
Dominik Laskowski7e045462018-05-30 13:02:02 -07001969 if (layer->getForceClientComposition(displayId)) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001970 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07001971 layer->setCompositionType(displayId, HWC2::Composition::Client);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001972 continue;
1973 }
1974
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001975 layer->setPerFrameData(display);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001976 }
1977
1978 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001979 ColorMode colorMode;
1980 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001981 RenderIntent renderIntent;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001982 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1983 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001984 }
1985 }
1986
Chia-I Wu28f320b2018-05-03 11:02:56 -07001987 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07001988
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001989 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001990 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001991 continue;
1992 }
1993
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001994 status_t result = display->prepareFrame(*getBE().mHwc);
1995 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001996 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001997 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001998}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001999
Mathias Agopiancd60f992012-08-16 16:28:27 -07002000void SurfaceFlinger::doComposition() {
2001 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002002 ALOGV("doComposition");
2003
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002004 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002005 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002006 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002007 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002008 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002009
2010 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002011 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002013 display->dirtyRegion.clear();
2014 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002015 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002016 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002017 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002018}
2019
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002020void SurfaceFlinger::postFramebuffer()
2021{
Mathias Agopian841cde52012-03-01 15:44:37 -08002022 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002023 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002024
Mathias Agopiana44b0412011-10-16 18:46:35 -07002025 const nsecs_t now = systemTime();
2026 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002027
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002028 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002029 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002030 continue;
2031 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002032 const auto displayId = display->getId();
2033 if (displayId >= 0) {
2034 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002035 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002036 display->onSwapBuffersCompleted();
2037 display->makeCurrent();
2038 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002039 // The layer buffer from the previous frame (if any) is released
2040 // by HWC only when the release fence from this frame (if any) is
2041 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002042 auto hwcLayer = layer->getHwcLayer(displayId);
2043 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002044
2045 // If the layer was client composited in the previous frame, we
2046 // need to merge with the previous client target acquire fence.
2047 // Since we do not track that, always merge with the current
2048 // client target acquire fence when it is available, even though
2049 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002050 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002051 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002052 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002053 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002054
David Sodmanb8af7922017-12-21 15:17:55 -08002055 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002056 }
Chia-I Wu83806892017-11-16 10:50:20 -08002057
2058 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002059 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002060 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002061 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002062 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002063 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002064 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002065 }
2066 }
2067
Dominik Laskowski7e045462018-05-30 13:02:02 -07002068 if (displayId >= 0) {
2069 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002070 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002071 }
2072
Mathias Agopiana44b0412011-10-16 18:46:35 -07002073 mLastSwapBufferTime = systemTime() - now;
2074 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002075
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002076 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002077 const auto display = getDefaultDisplayDeviceLocked();
2078 if (display && getHwComposer().isConnected(display->getId())) {
2079 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002080 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2081 logFrameStats();
2082 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002083 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002084}
2085
Mathias Agopian87baae12012-07-31 12:38:26 -07002086void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002087{
Mathias Agopian841cde52012-03-01 15:44:37 -08002088 ATRACE_CALL();
2089
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002090 // here we keep a copy of the drawing state (that is the state that's
2091 // going to be overwritten by handleTransactionLocked()) outside of
2092 // mStateLock so that the side-effects of the State assignment
2093 // don't happen with mStateLock held (which can cause deadlocks).
2094 State drawingState(mDrawingState);
2095
Mathias Agopianca4d3602011-05-19 15:38:14 -07002096 Mutex::Autolock _l(mStateLock);
2097 const nsecs_t now = systemTime();
2098 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002099
Mathias Agopianca4d3602011-05-19 15:38:14 -07002100 // Here we're guaranteed that some transaction flags are set
2101 // so we can call handleTransactionLocked() unconditionally.
2102 // We call getTransactionFlags(), which will also clear the flags,
2103 // with mStateLock held to guarantee that mCurrentState won't change
2104 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002105
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002106 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002107 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002108 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002109
Mathias Agopianca4d3602011-05-19 15:38:14 -07002110 mLastTransactionTime = systemTime() - now;
2111 mDebugInTransaction = 0;
2112 invalidateHwcGeometry();
2113 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002114}
2115
Dominik Laskowski7e045462018-05-30 13:02:02 -07002116DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002117 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002118 // Figure out whether the event is for the primary display or an
2119 // external display by matching the Hwc display id against one for a
2120 // connected display. If we did not find a match, we then check what
2121 // displays are not already connected to determine the type. If we don't
2122 // have a connected primary display, we assume the new display is meant to
2123 // be the primary display, and then if we don't have an external display,
2124 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002125 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2126 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002127 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002128 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002129 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002130 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002131 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002132 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002133 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002134 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002135 return DisplayDevice::DISPLAY_EXTERNAL;
2136 }
2137
2138 return DisplayDevice::DISPLAY_ID_INVALID;
2139}
2140
Lloyd Piqueba04e622017-12-14 17:11:26 -08002141void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2142 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002143 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002144 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002145 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002146 continue;
2147 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002148
2149 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2150 ALOGE("External displays are not supported by the vr hardware composer.");
2151 continue;
2152 }
2153
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002154 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002155 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002156 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002157 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002158 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002159
2160 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002161 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002162 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002163 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002164 DisplayDeviceState info;
2165 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002166 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2167 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002168 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002169 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002170 mInterceptor->saveDisplayCreation(info);
2171 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002172 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002173 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002174
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002175 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002176 if (idx >= 0) {
2177 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002178 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002179 mCurrentState.displays.removeItemsAt(idx);
2180 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002181 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002182 }
2183
2184 processDisplayChangesLocked();
2185 }
2186
2187 mPendingHotplugEvents.clear();
2188}
2189
Lloyd Pique99d3da52018-01-22 17:48:03 -08002190sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002191 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002192 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002193 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002194 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002195
Lloyd Pique99d3da52018-01-22 17:48:03 -08002196 if (hasWideColorDisplay) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002197 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002198 for (ColorMode colorMode : modes) {
2199 switch (colorMode) {
2200 case ColorMode::DISPLAY_P3:
2201 case ColorMode::ADOBE_RGB:
2202 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002203 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002204 break;
2205 default:
2206 break;
2207 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002208
Dominik Laskowski7e045462018-05-30 13:02:02 -07002209 std::vector<RenderIntent> renderIntents =
2210 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002211 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002212 }
2213 }
2214
Peiyong Lin62665892018-04-16 11:07:44 -07002215 HdrCapabilities hdrCapabilities;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002216 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002217
2218 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2219 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2220
2221 /*
2222 * Create our display's surface
2223 */
2224 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2225 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002226 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002227 renderSurface->setNativeWindow(nativeWindow.get());
2228 const int displayWidth = renderSurface->queryWidth();
2229 const int displayHeight = renderSurface->queryHeight();
2230
2231 // Make sure that composition can never be stalled by a virtual display
2232 // consumer that isn't processing buffers fast enough. We have to do this
2233 // in two places:
2234 // * Here, in case the display is composed entirely by HWC.
2235 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2236 // window's swap interval in eglMakeCurrent, so they'll override the
2237 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002238 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002239 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2240 }
2241
2242 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002243 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002244
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002245 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002246 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2247 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2248 displayHeight, hasWideColorGamut, hdrCapabilities,
2249 getHwComposer().getSupportedPerFrameMetadata(displayId),
2250 hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002251
2252 if (maxFrameBufferAcquiredBuffers >= 3) {
2253 nativeWindowSurface->preallocateBuffers();
2254 }
2255
2256 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002257 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2258 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002259 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002260 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002261 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002262 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002263 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002264 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002265 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002266 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002267 display->setLayerStack(state.layerStack);
2268 display->setProjection(state.orientation, state.viewport, state.frame);
2269 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002270
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002271 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002272}
2273
Lloyd Pique347200f2017-12-14 17:00:15 -08002274void SurfaceFlinger::processDisplayChangesLocked() {
2275 // here we take advantage of Vector's copy-on-write semantics to
2276 // improve performance by skipping the transaction entirely when
2277 // know that the lists are identical
2278 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2279 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2280 if (!curr.isIdenticalTo(draw)) {
2281 mVisibleRegionsDirty = true;
2282 const size_t cc = curr.size();
2283 size_t dc = draw.size();
2284
2285 // find the displays that were removed
2286 // (ie: in drawing state but not in current state)
2287 // also handle displays that changed
2288 // (ie: displays that are in both lists)
2289 for (size_t i = 0; i < dc;) {
2290 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2291 if (j < 0) {
2292 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002293 // Call makeCurrent() on the primary display so we can
2294 // be sure that nothing associated with this display
2295 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002296 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2297 defaultDisplay->makeCurrent();
2298 }
2299 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2300 display->disconnect(getHwComposer());
2301 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002302 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2303 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2304 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2305 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2306 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002307 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002308 } else {
2309 // this display is in both lists. see if something changed.
2310 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002311 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002312 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2313 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2314 if (state_binder != draw_binder) {
2315 // changing the surface is like destroying and
2316 // recreating the DisplayDevice, so we just remove it
2317 // from the drawing state, so that it get re-added
2318 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002319 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2320 display->disconnect(getHwComposer());
2321 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002322 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002323 mDrawingState.displays.removeItemsAt(i);
2324 dc--;
2325 // at this point we must loop to the next item
2326 continue;
2327 }
2328
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002329 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002330 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002331 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002332 }
2333 if ((state.orientation != draw[i].orientation) ||
2334 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002335 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002336 }
2337 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002338 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002339 }
2340 }
2341 }
2342 ++i;
2343 }
2344
2345 // find displays that were added
2346 // (ie: in current state but not in drawing state)
2347 for (size_t i = 0; i < cc; i++) {
2348 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2349 const DisplayDeviceState& state(curr[i]);
2350
2351 sp<DisplaySurface> dispSurface;
2352 sp<IGraphicBufferProducer> producer;
2353 sp<IGraphicBufferProducer> bqProducer;
2354 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002355 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002356
Dominik Laskowski7e045462018-05-30 13:02:02 -07002357 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002358 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002359 // Virtual displays without a surface are dormant:
2360 // they have external state (layer stack, projection,
2361 // etc.) but no internal state (i.e. a DisplayDevice).
2362 if (state.surface != nullptr) {
2363 // Allow VR composer to use virtual displays.
2364 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2365 int width = 0;
2366 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2367 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2368 int height = 0;
2369 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2370 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2371 int intFormat = 0;
2372 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2373 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002374 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002375
Dominik Laskowski7e045462018-05-30 13:02:02 -07002376 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2377 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002378 }
2379
2380 // TODO: Plumb requested format back up to consumer
2381
2382 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002383 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002384 bqProducer, bqConsumer,
2385 state.displayName);
2386
2387 dispSurface = vds;
2388 producer = vds;
2389 }
2390 } else {
2391 ALOGE_IF(state.surface != nullptr,
2392 "adding a supported display, but rendering "
2393 "surface is provided (%p), ignoring it",
2394 state.surface.get());
2395
Dominik Laskowski7e045462018-05-30 13:02:02 -07002396 displayId = state.type;
2397 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002398 producer = bqProducer;
2399 }
2400
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002401 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002402 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002403 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002404 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002405 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002406 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002407 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2408 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2409 true);
2410 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2411 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2412 true);
2413 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002414 }
2415 }
2416 }
2417 }
2418 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002419
2420 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002421}
2422
Mathias Agopian87baae12012-07-31 12:38:26 -07002423void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002424{
Dan Stoza7dde5992015-05-22 09:51:44 -07002425 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002426 mCurrentState.traverseInZOrder([](Layer* layer) {
2427 layer->notifyAvailableFrames();
2428 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002429
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002430 /*
2431 * Traversal of the children
2432 * (perform the transaction for each of them if needed)
2433 */
2434
Mathias Agopian3559b072012-08-15 13:46:03 -07002435 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002436 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002437 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002438 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002439
2440 const uint32_t flags = layer->doTransaction(0);
2441 if (flags & Layer::eVisibleRegion)
2442 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002443 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002444 }
2445
2446 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002447 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002448 */
2449
Mathias Agopiane57f2922012-08-09 16:29:12 -07002450 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002451 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002452 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002453 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002455 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002456 // The transform hint might have changed for some layers
2457 // (either because a display has changed, or because a layer
2458 // as changed).
2459 //
2460 // Walk through all the layers in currentLayers,
2461 // and update their transform hint.
2462 //
2463 // If a layer is visible only on a single display, then that
2464 // display is used to calculate the hint, otherwise we use the
2465 // default display.
2466 //
2467 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2468 // the hint is set before we acquire a buffer from the surface texture.
2469 //
2470 // NOTE: layer transactions have taken place already, so we use their
2471 // drawing state. However, SurfaceFlinger's own transaction has not
2472 // happened yet, so we must use the current state layer list
2473 // (soon to become the drawing state list).
2474 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002475 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002476 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002477 bool first = true;
2478 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002479 // NOTE: we rely on the fact that layers are sorted by
2480 // layerStack first (so we don't have to traverse the list
2481 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002482 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002483 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002484 currentlayerStack = layerStack;
2485 // figure out if this layerstack is mirrored
2486 // (more than one display) if so, pick the default display,
2487 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002488 hintDisplay = nullptr;
2489 for (const auto& [token, display] : mDisplays) {
2490 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2491 if (hintDisplay) {
2492 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002493 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002494 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002495 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002496 }
2497 }
2498 }
2499 }
Chet Haase91d25932013-04-11 15:24:55 -07002500
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002501 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002502 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2503 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002504
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002505 // could be null when this layer is using a layerStack
2506 // that is not visible on any display. Also can occur at
2507 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002508 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002509 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002510
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002511 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002512 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002513 if (hintDisplay) {
2514 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002515 }
Robert Carr2047fae2016-11-28 14:09:09 -08002516
2517 first = false;
2518 });
Mathias Agopian84300952012-11-21 16:02:13 -08002519 }
2520
2521
Mathias Agopian3559b072012-08-15 13:46:03 -07002522 /*
2523 * Perform our own transaction if needed
2524 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002525
2526 if (mLayersAdded) {
2527 mLayersAdded = false;
2528 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002529 mVisibleRegionsDirty = true;
2530 }
2531
2532 // some layers might have been removed, so
2533 // we need to update the regions they're exposing.
2534 if (mLayersRemoved) {
2535 mLayersRemoved = false;
2536 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002537 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002538 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002539 // this layer is not visible anymore
2540 // TODO: we could traverse the tree from front to back and
2541 // compute the actual visible region
2542 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002543 Region visibleReg;
2544 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002545 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002546 }
Robert Carr2047fae2016-11-28 14:09:09 -08002547 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002548 }
2549
2550 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002551
2552 updateCursorAsync();
2553}
2554
2555void SurfaceFlinger::updateCursorAsync()
2556{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002557 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002558 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002559 continue;
2560 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002561
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002562 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2563 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002564 }
2565 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002566}
2567
2568void SurfaceFlinger::commitTransaction()
2569{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002570 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002571 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002572 for (const auto& l : mLayersPendingRemoval) {
2573 recordBufferingStats(l->getName().string(),
2574 l->getOccupancyHistory(true));
2575 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002576 }
2577 mLayersPendingRemoval.clear();
2578 }
2579
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002580 // If this transaction is part of a window animation then the next frame
2581 // we composite should be considered an animation as well.
2582 mAnimCompositionPending = mAnimTransactionPending;
2583
Mathias Agopian4fec8732012-06-29 14:12:52 -07002584 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002585 // clear the "changed" flags in current state
2586 mCurrentState.colorMatrixChanged = false;
2587
Robert Carr1f0a16a2016-10-24 16:27:39 -07002588 mDrawingState.traverseInZOrder([](Layer* layer) {
2589 layer->commitChildList();
2590 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002591 mTransactionPending = false;
2592 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002593 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002594}
2595
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002596void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2597 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002598 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002599 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002600
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601 Region aboveOpaqueLayers;
2602 Region aboveCoveredLayers;
2603 Region dirty;
2604
Mathias Agopian87baae12012-07-31 12:38:26 -07002605 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606
Robert Carr2047fae2016-11-28 14:09:09 -08002607 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002609 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002610
Jesse Hall01e29052013-02-19 16:13:35 -08002611 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002612 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002613 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002614 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002615
Mathias Agopianab028732010-03-16 16:41:46 -07002616 /*
2617 * opaqueRegion: area of a surface that is fully opaque.
2618 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002619 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002620
2621 /*
2622 * visibleRegion: area of a surface that is visible on screen
2623 * and not fully transparent. This is essentially the layer's
2624 * footprint minus the opaque regions above it.
2625 * Areas covered by a translucent surface are considered visible.
2626 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002627 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002628
2629 /*
2630 * coveredRegion: area of a surface that is covered by all
2631 * visible regions above it (which includes the translucent areas).
2632 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002633 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002634
Jesse Halla8026d22012-09-25 13:25:04 -07002635 /*
2636 * transparentRegion: area of a surface that is hinted to be completely
2637 * transparent. This is only used to tell when the layer has no visible
2638 * non-transparent regions and can be removed from the layer list. It
2639 * does not affect the visibleRegion of this layer or any layers
2640 * beneath it. The hint may not be correct if apps don't respect the
2641 * SurfaceView restrictions (which, sadly, some don't).
2642 */
2643 Region transparentRegion;
2644
Mathias Agopianab028732010-03-16 16:41:46 -07002645
2646 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002647 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002648 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002649 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002650 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002651 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002652 if (!visibleRegion.isEmpty()) {
2653 // Remove the transparent area from the visible region
2654 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002655 if (tr.preserveRects()) {
2656 // transform the transparent region
2657 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002658 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002659 // transformation too complex, can't do the
2660 // transparent region optimization.
2661 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002662 }
Mathias Agopianab028732010-03-16 16:41:46 -07002663 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664
Mathias Agopianab028732010-03-16 16:41:46 -07002665 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002666 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002667 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002668 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2669 // the opaque region is the layer's footprint
2670 opaqueRegion = visibleRegion;
2671 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002672 }
2673 }
2674
Robert Carre5f4f692018-01-12 13:12:28 -08002675 if (visibleRegion.isEmpty()) {
2676 layer->clearVisibilityRegions();
2677 return;
2678 }
2679
Mathias Agopianab028732010-03-16 16:41:46 -07002680 // Clip the covered region to the visible region
2681 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2682
2683 // Update aboveCoveredLayers for next (lower) layer
2684 aboveCoveredLayers.orSelf(visibleRegion);
2685
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002686 // subtract the opaque region covered by the layers above us
2687 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002688
2689 // compute this layer's dirty region
2690 if (layer->contentDirty) {
2691 // we need to invalidate the whole region
2692 dirty = visibleRegion;
2693 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002694 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695 layer->contentDirty = false;
2696 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002697 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002698 * the exposed region consists of two components:
2699 * 1) what's VISIBLE now and was COVERED before
2700 * 2) what's EXPOSED now less what was EXPOSED before
2701 *
2702 * note that (1) is conservative, we start with the whole
2703 * visible region but only keep what used to be covered by
2704 * something -- which mean it may have been exposed.
2705 *
2706 * (2) handles areas that were not covered by anything but got
2707 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002708 */
Mathias Agopianab028732010-03-16 16:41:46 -07002709 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002710 const Region oldVisibleRegion = layer->visibleRegion;
2711 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002712 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2713 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714 }
2715 dirty.subtractSelf(aboveOpaqueLayers);
2716
2717 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002718 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719
Mathias Agopianab028732010-03-16 16:41:46 -07002720 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002722
Jesse Halla8026d22012-09-25 13:25:04 -07002723 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724 layer->setVisibleRegion(visibleRegion);
2725 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002726 layer->setVisibleNonTransparentRegion(
2727 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002728 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002729
Mathias Agopian87baae12012-07-31 12:38:26 -07002730 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731}
2732
Chia-I Wuab0c3192017-08-01 11:29:00 -07002733void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002734 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002735 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2736 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002737 }
2738 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002739}
2740
Dan Stoza6b9454d2014-11-07 16:00:59 -08002741bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002743 ALOGV("handlePageFlip");
2744
Brian Andersond6927fb2016-07-23 23:37:30 -07002745 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746
Mathias Agopian4fec8732012-06-29 14:12:52 -07002747 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002748 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002749 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002750
2751 // Store the set of layers that need updates. This set must not change as
2752 // buffers are being latched, as this could result in a deadlock.
2753 // Example: Two producers share the same command stream and:
2754 // 1.) Layer 0 is latched
2755 // 2.) Layer 0 gets a new frame
2756 // 2.) Layer 1 gets a new frame
2757 // 3.) Layer 1 is latched.
2758 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2759 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002760 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002761 if (layer->hasQueuedFrame()) {
2762 frameQueued = true;
2763 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002764 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002765 } else {
2766 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002767 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002768 } else {
2769 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002770 }
Robert Carr2047fae2016-11-28 14:09:09 -08002771 });
2772
Dan Stoza9e56aa02015-11-02 13:00:03 -08002773 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002774 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002775 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002776 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002777 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002778 newDataLatched = true;
2779 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002780 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002781
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002782 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002783
2784 // If we will need to wake up at some time in the future to deal with a
2785 // queued frame that shouldn't be displayed during this vsync period, wake
2786 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002787 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002788 signalLayerUpdate();
2789 }
2790
2791 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002792 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793}
2794
Mathias Agopianad456f92011-01-13 17:53:01 -08002795void SurfaceFlinger::invalidateHwcGeometry()
2796{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002797 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002798}
2799
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002800void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2801 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002802 // We only need to actually compose the display if:
2803 // 1) It is being handled by hardware composer, which may need this to
2804 // keep its virtual display state machine in sync, or
2805 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002806 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002807 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002808 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002809 return;
2810 }
2811
Dan Stoza9e56aa02015-11-02 13:00:03 -08002812 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002813 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002814
2815 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002816 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817}
2818
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002819bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002820 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002821
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002822 const Region bounds(display->bounds());
2823 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002824 const auto displayId = display->getId();
2825 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002826 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002827
Chia-I Wu8e50e692018-05-04 10:12:37 -07002828 bool applyColorMatrix = false;
Peiyong Lin00f9c022018-05-09 15:35:33 -07002829 bool needsLegacyColorMatrix = false;
2830 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002831
Dan Stoza9e56aa02015-11-02 13:00:03 -08002832 if (hasClientComposition) {
2833 ALOGV("hasClientComposition");
2834
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002835 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002836 if (display->hasWideColorGamut()) {
2837 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002838 }
2839 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002840 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002841 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002842
Dominik Laskowski7e045462018-05-30 13:02:02 -07002843 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002844 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2845 HWC2::Capability::SkipClientColorTransform);
2846
2847 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2848 if (applyColorMatrix) {
Peiyong Lin00f9c022018-05-09 15:35:33 -07002849 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002850 }
2851
Chia-I Wubbb44462018-05-21 15:33:27 -07002852 needsLegacyColorMatrix =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002853 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2854 outputDataspace != Dataspace::UNKNOWN && outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002855
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002856 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002857 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002858 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002859 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002860
2861 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002862 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2863 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2864 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002865 }
2866 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002867 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002868
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002869 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002870 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002871 // when using overlays, we assume a fully transparent framebuffer
2872 // NOTE: we could reduce how much we need to clear, for instance
2873 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002874 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002875 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002876 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002877 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002878 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002879 // we're left with the letterbox region
2880 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002881 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002882
2883 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002884 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002885
Mathias Agopianb9494d52012-04-18 02:28:45 -07002886 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002887 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002888 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002889 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002890 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002891 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002892
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002893 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002894 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002895 // scissor on the main display. It should never be needed
2896 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002897 const Rect& bounds = display->getBounds();
2898 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002899 if (scissor != bounds) {
2900 // scissor doesn't match the screen's dimensions, so we
2901 // need to clear everything outside of it and enable
2902 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002903
Mathias Agopianf45c5102012-10-24 16:29:17 -07002904 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002905 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002906 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002907 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002908 }
2909 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002910 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002911
Mathias Agopian85d751c2012-08-29 16:59:24 -07002912 /*
2913 * and then, render the layers targeted at the framebuffer
2914 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002915
Dan Stoza9e56aa02015-11-02 13:00:03 -08002916 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002917 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002918 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002919 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002920 const Region clip(bounds.intersect(
2921 displayTransform.transform(layer->visibleRegion)));
2922 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002923 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002924 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002925 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002926 case HWC2::Composition::Cursor:
2927 case HWC2::Composition::Device:
2928 case HWC2::Composition::Sideband:
2929 case HWC2::Composition::SolidColor: {
2930 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002931 if (layer->getClearClientTarget(displayId) && !firstLayer &&
2932 layer->isOpaque(state) && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002933 // never clear the very first layer since we're
2934 // guaranteed the FB is already cleared
2935 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002936 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002937 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002938 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002939 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002940 // switch color matrices lazily
Peiyong Lin00f9c022018-05-09 15:35:33 -07002941 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
2942 if (!legacyColorMatrixApplied) {
2943 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
2944 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002945 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07002946 } else if (legacyColorMatrixApplied) {
2947 getRenderEngine().setSaturationMatrix(mat4());
2948 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002949 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07002950
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002951 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002952 break;
2953 }
2954 default:
2955 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002956 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002957 } else {
2958 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002959 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002960 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002961 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002962
Peiyong Lin00f9c022018-05-09 15:35:33 -07002963 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002964 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002965 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07002966 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
2967 getRenderEngine().setSaturationMatrix(mat4());
2968 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002969
Mathias Agopianf45c5102012-10-24 16:29:17 -07002970 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002971 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002972 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002973}
2974
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002975void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2976 const Region& region) const {
2977 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002978 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002979 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002980}
2981
Dan Stoza7d89d062015-04-30 13:29:25 -07002982status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002983 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002984 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002985 const sp<Layer>& lbc,
2986 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002987{
Dan Stoza7d89d062015-04-30 13:29:25 -07002988 // add this layer to the current state list
2989 {
2990 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002991 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002992 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2993 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002994 return NO_MEMORY;
2995 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002996 if (parent == nullptr) {
2997 mCurrentState.layersSortedByZ.add(lbc);
2998 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002999 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003000 ALOGE("addClientLayer called with a removed parent");
3001 return NAME_NOT_FOUND;
3002 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003003 parent->addChild(lbc);
3004 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003005
Yiwei Zhang243b3782018-05-15 17:40:04 -07003006 if (gbc != nullptr) {
3007 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3008 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3009 mMaxGraphicBufferProducerListSize,
3010 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3011 mGraphicBufferProducerList.size(),
3012 mMaxGraphicBufferProducerListSize, mNumLayers);
3013 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003014 mLayersAdded = true;
3015 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003016 }
3017
Mathias Agopian96f08192010-06-02 23:28:45 -07003018 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003019 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003020
Dan Stoza7d89d062015-04-30 13:29:25 -07003021 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003022}
3023
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003024status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003025 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003026 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3027}
Robert Carr7f9b8992017-03-10 11:08:39 -08003028
chaviwca27f252018-02-06 16:46:39 -08003029status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3030 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003031 if (layer->isPendingRemoval()) {
3032 return NO_ERROR;
3033 }
3034
Robert Carr1f0a16a2016-10-24 16:27:39 -07003035 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003036 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003037 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003038 if (topLevelOnly) {
3039 return NO_ERROR;
3040 }
3041
Chia-I Wu98f1c102017-05-30 14:54:08 -07003042 sp<Layer> ancestor = p;
3043 while (ancestor->getParent() != nullptr) {
3044 ancestor = ancestor->getParent();
3045 }
3046 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3047 ALOGE("removeLayer called with a layer whose parent has been removed");
3048 return NAME_NOT_FOUND;
3049 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003050
3051 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003052 } else {
3053 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003054 }
3055
Robert Carr136e2f62017-02-08 17:54:29 -08003056 // As a matter of normal operation, the LayerCleaner will produce a second
3057 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3058 // so we will succeed in promoting it, but it's already been removed
3059 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3060 // otherwise something has gone wrong and we are leaking the layer.
3061 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003062 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3063 layer->getName().string(),
3064 (p != nullptr) ? p->getName().string() : "no-parent");
3065 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003066 } else if (index < 0) {
3067 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003068 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003069
Chia-I Wuc6657022017-08-15 11:18:17 -07003070 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003071 mLayersPendingRemoval.add(layer);
3072 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003073 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003074 setTransactionFlags(eTransactionNeeded);
3075 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076}
3077
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003078uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003079 return android_atomic_release_load(&mTransactionFlags);
3080}
3081
Mathias Agopian3f844832013-08-07 21:24:32 -07003082uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3084}
3085
Mathias Agopian3f844832013-08-07 21:24:32 -07003086uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003087 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3088}
3089
3090uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3091 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003093 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003094 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003095 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096 }
3097 return old;
3098}
3099
chaviwca27f252018-02-06 16:46:39 -08003100bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3101 for (const ComposerState& state : states) {
3102 // Here we need to check that the interface we're given is indeed
3103 // one of our own. A malicious client could give us a nullptr
3104 // IInterface, or one of its own or even one of our own but a
3105 // different type. All these situations would cause us to crash.
3106 if (state.client == nullptr) {
3107 return true;
3108 }
3109
3110 sp<IBinder> binder = IInterface::asBinder(state.client);
3111 if (binder == nullptr) {
3112 return true;
3113 }
3114
3115 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3116 return true;
3117 }
3118 }
3119 return false;
3120}
3121
Mathias Agopian8b33f032012-07-24 20:43:54 -07003122void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003123 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003124 const Vector<DisplayState>& displays,
3125 uint32_t flags)
3126{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003127 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003128 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003129 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003130
chaviwca27f252018-02-06 16:46:39 -08003131 if (containsAnyInvalidClientState(states)) {
3132 return;
3133 }
3134
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003135 if (flags & eAnimation) {
3136 // For window updates that are part of an animation we must wait for
3137 // previous animation "frames" to be handled.
3138 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003139 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003140 if (CC_UNLIKELY(err != NO_ERROR)) {
3141 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003142 // caller after a few seconds.
3143 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3144 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003145 mAnimTransactionPending = false;
3146 break;
3147 }
3148 }
3149 }
3150
chaviwca27f252018-02-06 16:46:39 -08003151 for (const DisplayState& display : displays) {
3152 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003153 }
3154
chaviwca27f252018-02-06 16:46:39 -08003155 for (const ComposerState& state : states) {
3156 transactionFlags |= setClientStateLocked(state);
3157 }
3158
3159 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3160 // as destroyed should only occur after setting all other states. This is to allow for a
3161 // child re-parent to happen before marking its original parent as destroyed (which would
3162 // then mark the child as destroyed).
3163 for (const ComposerState& state : states) {
3164 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003165 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003166
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003167 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3168 // anyway. This can be used as a flush mechanism for previous async transactions.
3169 // Empty animation transaction can be used to simulate back-pressure, so also force a
3170 // transaction for empty animation transactions.
3171 if (transactionFlags == 0 &&
3172 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003173 transactionFlags = eTransactionNeeded;
3174 }
3175
Mathias Agopian386aa982011-11-07 21:58:03 -08003176 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003177 if (mInterceptor->isEnabled()) {
3178 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003179 }
Irvel468051e2016-06-13 16:44:44 -07003180
Mathias Agopian386aa982011-11-07 21:58:03 -08003181 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003182 const auto start = (flags & eEarlyWakeup)
3183 ? VSyncModulator::TransactionStart::EARLY
3184 : VSyncModulator::TransactionStart::NORMAL;
3185 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003186
3187 // if this is a synchronous transaction, wait for it to take effect
3188 // before returning.
3189 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003190 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003191 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003192 if (flags & eAnimation) {
3193 mAnimTransactionPending = true;
3194 }
3195 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003196 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3197 if (CC_UNLIKELY(err != NO_ERROR)) {
3198 // just in case something goes wrong in SF, return to the
3199 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003200 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3201 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003202 break;
3203 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003204 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003205 }
3206}
3207
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003208uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3209 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3210 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003211
Mathias Agopiane57f2922012-08-09 16:29:12 -07003212 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003213 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3214
3215 const uint32_t what = s.what;
3216 if (what & DisplayState::eSurfaceChanged) {
3217 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3218 state.surface = s.surface;
3219 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003220 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003221 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003222 if (what & DisplayState::eLayerStackChanged) {
3223 if (state.layerStack != s.layerStack) {
3224 state.layerStack = s.layerStack;
3225 flags |= eDisplayTransactionNeeded;
3226 }
3227 }
3228 if (what & DisplayState::eDisplayProjectionChanged) {
3229 if (state.orientation != s.orientation) {
3230 state.orientation = s.orientation;
3231 flags |= eDisplayTransactionNeeded;
3232 }
3233 if (state.frame != s.frame) {
3234 state.frame = s.frame;
3235 flags |= eDisplayTransactionNeeded;
3236 }
3237 if (state.viewport != s.viewport) {
3238 state.viewport = s.viewport;
3239 flags |= eDisplayTransactionNeeded;
3240 }
3241 }
3242 if (what & DisplayState::eDisplaySizeChanged) {
3243 if (state.width != s.width) {
3244 state.width = s.width;
3245 flags |= eDisplayTransactionNeeded;
3246 }
3247 if (state.height != s.height) {
3248 state.height = s.height;
3249 flags |= eDisplayTransactionNeeded;
3250 }
3251 }
3252
Mathias Agopiane57f2922012-08-09 16:29:12 -07003253 return flags;
3254}
3255
chaviwca27f252018-02-06 16:46:39 -08003256uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3257 const layer_state_t& s = composerState.state;
3258 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3259
Mathias Agopian13127d82013-03-05 17:47:11 -08003260 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003261 if (layer == nullptr) {
3262 return 0;
3263 }
3264
3265 if (layer->isPendingRemoval()) {
3266 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3267 return 0;
3268 }
3269
3270 uint32_t flags = 0;
3271
3272 const uint32_t what = s.what;
3273 bool geometryAppliesWithResize =
3274 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003275
3276 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3277 // pending state will also be deferred.
3278 if (what & layer_state_t::eDeferTransaction) {
3279 layer->pushPendingState();
3280 }
3281
chaviw8b3871a2017-11-01 17:41:01 -07003282 if (what & layer_state_t::ePositionChanged) {
3283 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3284 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003285 }
chaviw8b3871a2017-11-01 17:41:01 -07003286 }
3287 if (what & layer_state_t::eLayerChanged) {
3288 // NOTE: index needs to be calculated before we update the state
3289 const auto& p = layer->getParent();
3290 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003291 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003292 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003293 mCurrentState.layersSortedByZ.removeAt(idx);
3294 mCurrentState.layersSortedByZ.add(layer);
3295 // we need traversal (state changed)
3296 // AND transaction (list changed)
3297 flags |= eTransactionNeeded|eTraversalNeeded;
3298 }
chaviw8b3871a2017-11-01 17:41:01 -07003299 } else {
3300 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003301 flags |= eTransactionNeeded|eTraversalNeeded;
3302 }
3303 }
chaviw8b3871a2017-11-01 17:41:01 -07003304 }
3305 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003306 // NOTE: index needs to be calculated before we update the state
3307 const auto& p = layer->getParent();
3308 if (p == nullptr) {
3309 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3310 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3311 mCurrentState.layersSortedByZ.removeAt(idx);
3312 mCurrentState.layersSortedByZ.add(layer);
3313 // we need traversal (state changed)
3314 // AND transaction (list changed)
3315 flags |= eTransactionNeeded|eTraversalNeeded;
3316 }
3317 } else {
3318 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3319 flags |= eTransactionNeeded|eTraversalNeeded;
3320 }
chaviw8b3871a2017-11-01 17:41:01 -07003321 }
3322 }
3323 if (what & layer_state_t::eSizeChanged) {
3324 if (layer->setSize(s.w, s.h)) {
3325 flags |= eTraversalNeeded;
3326 }
3327 }
3328 if (what & layer_state_t::eAlphaChanged) {
3329 if (layer->setAlpha(s.alpha))
3330 flags |= eTraversalNeeded;
3331 }
3332 if (what & layer_state_t::eColorChanged) {
3333 if (layer->setColor(s.color))
3334 flags |= eTraversalNeeded;
3335 }
3336 if (what & layer_state_t::eMatrixChanged) {
3337 if (layer->setMatrix(s.matrix))
3338 flags |= eTraversalNeeded;
3339 }
3340 if (what & layer_state_t::eTransparentRegionChanged) {
3341 if (layer->setTransparentRegionHint(s.transparentRegion))
3342 flags |= eTraversalNeeded;
3343 }
3344 if (what & layer_state_t::eFlagsChanged) {
3345 if (layer->setFlags(s.flags, s.mask))
3346 flags |= eTraversalNeeded;
3347 }
3348 if (what & layer_state_t::eCropChanged) {
3349 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3350 flags |= eTraversalNeeded;
3351 }
3352 if (what & layer_state_t::eFinalCropChanged) {
3353 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3354 flags |= eTraversalNeeded;
3355 }
3356 if (what & layer_state_t::eLayerStackChanged) {
3357 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3358 // We only allow setting layer stacks for top level layers,
3359 // everything else inherits layer stack from its parent.
3360 if (layer->hasParent()) {
3361 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3362 layer->getName().string());
3363 } else if (idx < 0) {
3364 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3365 "that also does not appear in the top level layer list. Something"
3366 " has gone wrong.", layer->getName().string());
3367 } else if (layer->setLayerStack(s.layerStack)) {
3368 mCurrentState.layersSortedByZ.removeAt(idx);
3369 mCurrentState.layersSortedByZ.add(layer);
3370 // we need traversal (state changed)
3371 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003372 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003373 }
3374 }
3375 if (what & layer_state_t::eDeferTransaction) {
3376 if (s.barrierHandle != nullptr) {
3377 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3378 } else if (s.barrierGbp != nullptr) {
3379 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3380 if (authenticateSurfaceTextureLocked(gbp)) {
3381 const auto& otherLayer =
3382 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3383 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3384 } else {
3385 ALOGE("Attempt to defer transaction to to an"
3386 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003387 }
3388 }
chaviw8b3871a2017-11-01 17:41:01 -07003389 // We don't trigger a traversal here because if no other state is
3390 // changed, we don't want this to cause any more work
3391 }
3392 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003393 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003394 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003395 if (!hadParent) {
3396 mCurrentState.layersSortedByZ.remove(layer);
3397 }
chaviw8b3871a2017-11-01 17:41:01 -07003398 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003399 }
chaviw8b3871a2017-11-01 17:41:01 -07003400 }
3401 if (what & layer_state_t::eReparentChildren) {
3402 if (layer->reparentChildren(s.reparentHandle)) {
3403 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003404 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003405 }
chaviw8b3871a2017-11-01 17:41:01 -07003406 if (what & layer_state_t::eDetachChildren) {
3407 layer->detachChildren();
3408 }
3409 if (what & layer_state_t::eOverrideScalingModeChanged) {
3410 layer->setOverrideScalingMode(s.overrideScalingMode);
3411 // We don't trigger a traversal here because if no other state is
3412 // changed, we don't want this to cause any more work
3413 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003414 return flags;
3415}
3416
chaviwca27f252018-02-06 16:46:39 -08003417void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3418 const layer_state_t& state = composerState.state;
3419 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3420
3421 sp<Layer> layer(client->getLayerUser(state.surface));
3422 if (layer == nullptr) {
3423 return;
3424 }
3425
3426 if (layer->isPendingRemoval()) {
3427 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3428 return;
3429 }
3430
3431 if (state.what & layer_state_t::eDestroySurface) {
3432 removeLayerLocked(mStateLock, layer);
3433 }
3434}
3435
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003436status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003437 const String8& name,
3438 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003439 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003440 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003441 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003442{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003443 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003444 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003445 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003446 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003447 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003448
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003449 status_t result = NO_ERROR;
3450
3451 sp<Layer> layer;
3452
Cody Northropbc755282017-03-31 12:00:08 -06003453 String8 uniqueName = getUniqueLayerName(name);
3454
Mathias Agopian3165cc22012-08-08 19:42:09 -07003455 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3456 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003457 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003458 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003459 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003460
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003461 break;
chaviw13fdc492017-06-27 12:40:18 -07003462 case ISurfaceComposerClient::eFXSurfaceColor:
3463 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003464 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003465 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003466 break;
3467 default:
3468 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003469 break;
3470 }
3471
Dan Stoza7d89d062015-04-30 13:29:25 -07003472 if (result != NO_ERROR) {
3473 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003474 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003475
Chia-I Wuab0c3192017-08-01 11:29:00 -07003476 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3477 // TODO b/64227542
3478 if (windowType == 441731) {
3479 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3480 layer->setPrimaryDisplayOnly();
3481 }
3482
Albert Chaulk479c60c2017-01-27 14:21:34 -05003483 layer->setInfo(windowType, ownerUid);
3484
Robert Carr1f0a16a2016-10-24 16:27:39 -07003485 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003486 if (result != NO_ERROR) {
3487 return result;
3488 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003489 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003490
3491 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003492 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003493}
3494
Cody Northropbc755282017-03-31 12:00:08 -06003495String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3496{
3497 bool matchFound = true;
3498 uint32_t dupeCounter = 0;
3499
3500 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3501 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3502
3503 // Loop over layers until we're sure there is no matching name
3504 while (matchFound) {
3505 matchFound = false;
3506 mDrawingState.traverseInZOrder([&](Layer* layer) {
3507 if (layer->getName() == uniqueName) {
3508 matchFound = true;
3509 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3510 }
3511 });
3512 }
3513
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003514 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3515 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003516
3517 return uniqueName;
3518}
3519
David Sodman0c69cad2017-08-21 12:12:51 -07003520status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003521 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3522 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003523{
3524 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003525 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003526 case PIXEL_FORMAT_TRANSPARENT:
3527 case PIXEL_FORMAT_TRANSLUCENT:
3528 format = PIXEL_FORMAT_RGBA_8888;
3529 break;
3530 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003531 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003532 break;
3533 }
3534
David Sodman0c69cad2017-08-21 12:12:51 -07003535 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3536 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003537 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003538 *handle = layer->getHandle();
3539 *gbp = layer->getProducer();
3540 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003541 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003542
David Sodman0c69cad2017-08-21 12:12:51 -07003543 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003544 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003545}
3546
chaviw13fdc492017-06-27 12:40:18 -07003547status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003548 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003549 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003550{
chaviw13fdc492017-06-27 12:40:18 -07003551 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003552 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003553 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003554}
3555
Mathias Agopianac9fa422013-02-11 16:40:36 -08003556status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003557{
Robert Carr9524cb32017-02-13 11:32:32 -08003558 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003559 status_t err = NO_ERROR;
3560 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003561 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003562 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003563 err = removeLayer(l);
3564 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3565 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003566 }
3567 return err;
3568}
3569
Mathias Agopian13127d82013-03-05 17:47:11 -08003570status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003571{
Mathias Agopian67106042013-03-14 19:18:13 -07003572 // called by ~LayerCleaner() when all references to the IBinder (handle)
3573 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003574 sp<Layer> l = layer.promote();
3575 if (l == nullptr) {
3576 // The layer has already been removed, carry on
3577 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003578 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003579 // If we have a parent, then we can continue to live as long as it does.
3580 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003581}
3582
Mathias Agopianb60314a2012-04-10 22:09:54 -07003583// ---------------------------------------------------------------------------
3584
Andy McFadden13a082e2012-08-24 10:16:42 -07003585void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003586 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3587 if (!displayToken) return;
3588
Jesse Hall01e29052013-02-19 16:13:35 -08003589 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003590 Vector<ComposerState> state;
3591 Vector<DisplayState> displays;
3592 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003593 d.what = DisplayState::eDisplayProjectionChanged |
3594 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003595 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003596 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003597 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003598 d.frame.makeInvalid();
3599 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003600 d.width = 0;
3601 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003602 displays.add(d);
3603 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003604
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003605 const auto display = getDisplayDevice(displayToken);
3606 if (!display) return;
3607
3608 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3609
3610 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003611 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003612 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003613
Brian Andersond0010582017-03-07 13:20:31 -08003614 // Use phase of 0 since phase is not known.
3615 // Use latency of 0, which will snap to the ideal latency.
3616 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003617}
3618
3619void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003620 // Async since we may be called from the main thread.
3621 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003622}
3623
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003624void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3625 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003626 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003627 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003628
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003629 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003630 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003631 return;
3632 }
3633
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003634 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003635 ALOGW("Trying to set power mode for virtual display");
3636 return;
3637 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003638
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003639 display->setPowerMode(mode);
3640
Lloyd Pique4dccc412018-01-22 17:21:36 -08003641 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003642 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003643 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003644 if (idx < 0) {
3645 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3646 return;
3647 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003648 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003649 }
3650
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003651 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003652 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003653 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003654 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003655 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003656 // FIXME: eventthread only knows about the main display right now
3657 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003658 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003659 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003660
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003661 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003662 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003663 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003664
3665 struct sched_param param = {0};
3666 param.sched_priority = 1;
3667 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3668 ALOGW("Couldn't set SCHED_FIFO on display on");
3669 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003670 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003671 // Turn off the display
3672 struct sched_param param = {0};
3673 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3674 ALOGW("Couldn't set SCHED_OTHER on display off");
3675 }
3676
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003677 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003678 disableHardwareVsync(true); // also cancels any in-progress resync
3679
Mathias Agopiancde87a32012-09-13 14:09:01 -07003680 // FIXME: eventthread only knows about the main display right now
3681 mEventThread->onScreenReleased();
3682 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003683
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003684 getHwComposer().setPowerMode(type, mode);
3685 mVisibleRegionsDirty = true;
3686 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003687 } else if (mode == HWC_POWER_MODE_DOZE ||
3688 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003689 // Update display while dozing
3690 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003691 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003692 // FIXME: eventthread only knows about the main display right now
3693 mEventThread->onScreenAcquired();
3694 resyncToHardwareVsync(true);
3695 }
3696 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3697 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003698 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003699 disableHardwareVsync(true); // also cancels any in-progress resync
3700 // FIXME: eventthread only knows about the main display right now
3701 mEventThread->onScreenReleased();
3702 }
3703 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003704 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003705 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003706 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003707 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003708
3709 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003710}
3711
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003712void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003713 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003714 const auto display = getDisplayDevice(displayToken);
3715 if (!display) {
3716 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3717 displayToken.get());
3718 } else if (display->isVirtual()) {
3719 ALOGW("Attempt to set power mode %d for virtual display", mode);
3720 } else {
3721 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003722 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003723 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003724}
3725
3726// ---------------------------------------------------------------------------
3727
Lloyd Pique755e3192018-01-31 16:46:15 -08003728status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3729 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003730 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003731
Mathias Agopianbd115332013-04-18 16:41:04 -07003732 IPCThreadState* ipc = IPCThreadState::self();
3733 const int pid = ipc->getCallingPid();
3734 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003735
Mathias Agopianbd115332013-04-18 16:41:04 -07003736 if ((uid != AID_SHELL) &&
3737 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003738 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003739 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003740 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003741 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003742 // (this would indicate SF is stuck, but we want to be able to
3743 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003744 status_t err = mStateLock.timedLock(s2ns(1));
3745 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003746 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003747 result.appendFormat(
3748 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3749 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003750 }
3751
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003752 bool dumpAll = true;
3753 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003754 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003755
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003756 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003757 if ((index < numArgs) &&
3758 (args[index] == String16("--list"))) {
3759 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003760 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003761 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003762 }
3763
3764 if ((index < numArgs) &&
3765 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003766 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003767 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003768 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003769 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003770
3771 if ((index < numArgs) &&
3772 (args[index] == String16("--latency-clear"))) {
3773 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003774 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003775 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003776 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003777
3778 if ((index < numArgs) &&
3779 (args[index] == String16("--dispsync"))) {
3780 index++;
3781 mPrimaryDispSync.dump(result);
3782 dumpAll = false;
3783 }
Dan Stozab90cf072015-03-05 11:05:59 -08003784
3785 if ((index < numArgs) &&
3786 (args[index] == String16("--static-screen"))) {
3787 index++;
3788 dumpStaticScreenStats(result);
3789 dumpAll = false;
3790 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003791
3792 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003793 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003794 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003795 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003796 dumpAll = false;
3797 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003798
3799 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3800 index++;
3801 dumpWideColorInfo(result);
3802 dumpAll = false;
3803 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003804
3805 if ((index < numArgs) &&
3806 (args[index] == String16("--enable-layer-stats"))) {
3807 index++;
3808 mLayerStats.enable();
3809 dumpAll = false;
3810 }
3811
3812 if ((index < numArgs) &&
3813 (args[index] == String16("--disable-layer-stats"))) {
3814 index++;
3815 mLayerStats.disable();
3816 dumpAll = false;
3817 }
3818
3819 if ((index < numArgs) &&
3820 (args[index] == String16("--clear-layer-stats"))) {
3821 index++;
3822 mLayerStats.clear();
3823 dumpAll = false;
3824 }
3825
3826 if ((index < numArgs) &&
3827 (args[index] == String16("--dump-layer-stats"))) {
3828 index++;
3829 mLayerStats.dump(result);
3830 dumpAll = false;
3831 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003832
3833 if ((index < numArgs) &&
3834 (args[index] == String16("--display-identification"))) {
3835 index++;
3836 dumpDisplayIdentificationData(result);
3837 dumpAll = false;
3838 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003839
3840 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3841 index++;
3842 mTimeStats.parseArgs(asProto, args, index, result);
3843 dumpAll = false;
3844 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003845 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003846
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003847 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003848 if (asProto) {
3849 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3850 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3851 } else {
3852 dumpAllLocked(args, index, result);
3853 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003854 }
3855
Mathias Agopian9795c422009-08-26 16:36:26 -07003856 if (locked) {
3857 mStateLock.unlock();
3858 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003859 }
3860 write(fd, result.string(), result.size());
3861 return NO_ERROR;
3862}
3863
Dan Stozac7014012014-02-14 15:03:43 -08003864void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3865 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003866{
Robert Carr2047fae2016-11-28 14:09:09 -08003867 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003868 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003869 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003870}
3871
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003872void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003873 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003874{
3875 String8 name;
3876 if (index < args.size()) {
3877 name = String8(args[index]);
3878 index++;
3879 }
3880
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003881 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3882 getHwComposer().isConnected(displayId)) {
3883 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3884 const nsecs_t period = activeConfig->getVsyncPeriod();
3885 result.appendFormat("%" PRId64 "\n", period);
3886 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003887
3888 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003889 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003890 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003891 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003892 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003893 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003894 }
Robert Carr2047fae2016-11-28 14:09:09 -08003895 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003896 }
3897}
3898
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003899void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003900 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003901{
3902 String8 name;
3903 if (index < args.size()) {
3904 name = String8(args[index]);
3905 index++;
3906 }
3907
Robert Carr2047fae2016-11-28 14:09:09 -08003908 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003909 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003910 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003911 }
Robert Carr2047fae2016-11-28 14:09:09 -08003912 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003913
Svetoslavd85084b2014-03-20 10:28:31 -07003914 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003915}
3916
Jamie Gennis6547ff42013-07-16 20:12:42 -07003917// This should only be called from the main thread. Otherwise it would need
3918// the lock and should use mCurrentState rather than mDrawingState.
3919void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003920 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003921 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003922 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003923
3924 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3925}
3926
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003927void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003928{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003929 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003930
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003931 if (isLayerTripleBufferingDisabled())
3932 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003933
3934 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003935 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003936 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003937 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003938 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3939 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003940 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003941}
3942
Dan Stozab90cf072015-03-05 11:05:59 -08003943void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3944{
3945 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003946 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3947 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003948 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003949 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003950 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3951 b + 1, bucketTimeSec, percent);
3952 }
David Sodman4a36e932017-11-07 14:29:47 -08003953 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003954 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003955 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003956 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003957 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003958}
3959
Dan Stozae77c7662016-05-13 11:37:28 -07003960void SurfaceFlinger::recordBufferingStats(const char* layerName,
3961 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003962 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3963 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003964 for (const auto& segment : history) {
3965 if (!segment.usedThirdBuffer) {
3966 stats.twoBufferTime += segment.totalTime;
3967 }
3968 if (segment.occupancyAverage < 1.0f) {
3969 stats.doubleBufferedTime += segment.totalTime;
3970 } else if (segment.occupancyAverage < 2.0f) {
3971 stats.tripleBufferedTime += segment.totalTime;
3972 }
3973 ++stats.numSegments;
3974 stats.totalTime += segment.totalTime;
3975 }
3976}
3977
Brian Andersond6927fb2016-07-23 23:37:30 -07003978void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3979 result.appendFormat("Layer frame timestamps:\n");
3980
3981 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3982 const size_t count = currentLayers.size();
3983 for (size_t i=0 ; i<count ; i++) {
3984 currentLayers[i]->dumpFrameEvents(result);
3985 }
3986}
3987
Dan Stozae77c7662016-05-13 11:37:28 -07003988void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3989 result.append("Buffering stats:\n");
3990 result.append(" [Layer name] <Active time> <Two buffer> "
3991 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003992 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003993 typedef std::tuple<std::string, float, float, float> BufferTuple;
3994 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003995 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003996 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003997 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003998 if (stats.numSegments == 0) {
3999 continue;
4000 }
4001 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4002 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4003 stats.totalTime;
4004 float doubleBufferRatio = static_cast<float>(
4005 stats.doubleBufferedTime) / stats.totalTime;
4006 float tripleBufferRatio = static_cast<float>(
4007 stats.tripleBufferedTime) / stats.totalTime;
4008 sorted.insert({activeTime, {name, twoBufferRatio,
4009 doubleBufferRatio, tripleBufferRatio}});
4010 }
4011 for (const auto& sortedPair : sorted) {
4012 float activeTime = sortedPair.first;
4013 const BufferTuple& values = sortedPair.second;
4014 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4015 std::get<0>(values).c_str(), activeTime,
4016 std::get<1>(values), std::get<2>(values),
4017 std::get<3>(values));
4018 }
4019 result.append("\n");
4020}
4021
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004022void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004023 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004024 const int32_t displayId = display->getId();
4025 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4026 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004027 continue;
4028 }
4029
Dominik Laskowski7e045462018-05-30 13:02:02 -07004030 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004031 uint8_t port;
4032 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004033 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004034 result.append("no identification data\n");
4035 continue;
4036 }
4037
4038 if (!isEdid(data)) {
4039 result.append("unknown identification data: ");
4040 for (uint8_t byte : data) {
4041 result.appendFormat("%x ", byte);
4042 }
4043 result.append("\n");
4044 continue;
4045 }
4046
4047 const auto edid = parseEdid(data);
4048 if (!edid) {
4049 result.append("invalid EDID: ");
4050 for (uint8_t byte : data) {
4051 result.appendFormat("%x ", byte);
4052 }
4053 result.append("\n");
4054 continue;
4055 }
4056
4057 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4058 result.append(edid->displayName.data(), edid->displayName.length());
4059 result.append("\"\n");
4060 }
4061 result.append("\n");
4062}
4063
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004064void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4065 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004066 result.appendFormat("DisplayColorSetting: %s\n",
4067 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004068
4069 // TODO: print out if wide-color mode is active or not
4070
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004071 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004072 const int32_t displayId = display->getId();
4073 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004074 continue;
4075 }
4076
Dominik Laskowski7e045462018-05-30 13:02:02 -07004077 result.appendFormat("Display %d color modes:\n", displayId);
4078 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004079 for (auto&& mode : modes) {
4080 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4081 }
4082
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004083 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004084 result.appendFormat(" Current color mode: %s (%d)\n",
4085 decodeColorMode(currentMode).c_str(), currentMode);
4086 }
4087 result.append("\n");
4088}
4089
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004090LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004091 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004092 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4093 const State& state = useDrawing ? mDrawingState : mCurrentState;
4094 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004095 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004096 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004097 });
4098
4099 return layersProto;
4100}
4101
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004102LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004103 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004104
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004105 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004106 resolution->set_w(display.getWidth());
4107 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004108
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004109 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4110 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4111 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004112
Dominik Laskowski7e045462018-05-30 13:02:02 -07004113 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004114 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004115 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004116 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004117 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004118 }
4119 });
4120
4121 return layersProto;
4122}
4123
Mathias Agopian74d211a2013-04-22 16:55:35 +02004124void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4125 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004126{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004127 bool colorize = false;
4128 if (index < args.size()
4129 && (args[index] == String16("--color"))) {
4130 colorize = true;
4131 index++;
4132 }
4133
4134 Colorizer colorizer(colorize);
4135
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004136 // figure out if we're stuck somewhere
4137 const nsecs_t now = systemTime();
4138 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4139 const nsecs_t inTransaction(mDebugInTransaction);
4140 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4141 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4142
4143 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004144 * Dump library configuration.
4145 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004146
4147 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004148 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004149 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004150 appendSfConfigString(result);
4151 appendUiConfigString(result);
4152 appendGuiConfigString(result);
4153 result.append("\n");
4154
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004155 result.append("\nDisplay identification data:\n");
4156 dumpDisplayIdentificationData(result);
4157
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004158 result.append("\nWide-Color information:\n");
4159 dumpWideColorInfo(result);
4160
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004161 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004162 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004163 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004164 result.append(SyncFeatures::getInstance().toString());
4165 result.append("\n");
4166
Andy McFadden41d67d72014-04-25 16:58:34 -07004167 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004168 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004169 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004170
4171 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4172 getHwComposer().isConnected(displayId)) {
4173 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
4174 result.appendFormat("Display %d: app phase %" PRId64 " ns, sf phase %" PRId64
4175 " ns, early sf phase %" PRId64 " ns, present offset %" PRId64
4176 " ns (refresh %" PRId64 " ns)",
4177 displayId, vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4178 mVsyncModulator.getEarlyPhaseOffset(), dispSyncPresentTimeOffset,
4179 activeConfig->getVsyncPeriod());
4180 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004181 result.append("\n");
4182
Dan Stozab90cf072015-03-05 11:05:59 -08004183 // Dump static screen stats
4184 result.append("\n");
4185 dumpStaticScreenStats(result);
4186 result.append("\n");
4187
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004188 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4189
Dan Stozae77c7662016-05-13 11:37:28 -07004190 dumpBufferingStats(result);
4191
Andy McFadden4803b742012-09-24 19:07:20 -07004192 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004193 * Dump the visible layer list
4194 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004195 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004196 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004197 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4198 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004199 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004200
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004201 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004202 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004203 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004204 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004205
4206 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004207 * Dump Display state
4208 */
4209
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004210 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004211 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004212 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004213 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004214 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004215 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004216 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004217
4218 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004219 * Dump SurfaceFlinger global state
4220 */
4221
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004222 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004223 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004224 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004225
Mathias Agopian888c8222012-08-04 21:10:38 -07004226 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004227 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004228
David Sodmanbc815282017-11-05 18:57:52 -08004229 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004230
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004231 if (display) {
4232 display->undefinedRegion.dump(result, "undefinedRegion");
4233 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4234 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004235 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004236 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4237 " last transaction time : %f us\n"
4238 " transaction-flags : %08x\n"
4239 " gpu_to_cpu_unsupported : %d\n",
4240 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4241 mTransactionFlags, !mGpuToCpuSupported);
4242
4243 if (display) {
4244 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4245 result.appendFormat(" refresh-rate : %f fps\n"
4246 " x-dpi : %f\n"
4247 " y-dpi : %f\n",
4248 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4249 activeConfig->getDpiY());
4250 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004251
Mathias Agopian74d211a2013-04-22 16:55:35 +02004252 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004253 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004254
Mathias Agopian74d211a2013-04-22 16:55:35 +02004255 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004256 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004257
4258 /*
4259 * VSYNC state
4260 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004261 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004262 result.append("\n");
4263
4264 /*
4265 * HWC layer minidump
4266 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004267 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004268 const int32_t displayId = display->getId();
4269 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004270 continue;
4271 }
4272
Dominik Laskowski7e045462018-05-30 13:02:02 -07004273 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004274 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004275 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004276 result.append("\n");
4277 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004278
4279 /*
4280 * Dump HWComposer state
4281 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004282 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004283 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004284 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004285 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004286 result.appendFormat(" h/w composer %s\n",
4287 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004288 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004289
4290 /*
4291 * Dump gralloc state
4292 */
4293 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4294 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004295
4296 /*
4297 * Dump VrFlinger state if in use.
4298 */
4299 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4300 result.append("VrFlinger state:\n");
4301 result.append(mVrFlinger->Dump().c_str());
4302 result.append("\n");
4303 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004304}
4305
Dominik Laskowski7e045462018-05-30 13:02:02 -07004306const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004307 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004308 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004309 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004310 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004311 }
4312 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004313
4314 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4315 static const Vector<sp<Layer>> empty;
4316 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004317}
4318
Keun young Park63f165f2012-08-31 10:53:36 -07004319bool SurfaceFlinger::startDdmConnection()
4320{
4321 void* libddmconnection_dso =
4322 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4323 if (!libddmconnection_dso) {
4324 return false;
4325 }
4326 void (*DdmConnection_start)(const char* name);
4327 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004328 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004329 if (!DdmConnection_start) {
4330 dlclose(libddmconnection_dso);
4331 return false;
4332 }
4333 (*DdmConnection_start)(getServiceName());
4334 return true;
4335}
4336
Chia-I Wu28f320b2018-05-03 11:02:56 -07004337void SurfaceFlinger::updateColorMatrixLocked() {
4338 mat4 colorMatrix;
4339 if (mGlobalSaturationFactor != 1.0f) {
4340 // Rec.709 luma coefficients
4341 float3 luminance{0.213f, 0.715f, 0.072f};
4342 luminance *= 1.0f - mGlobalSaturationFactor;
4343 mat4 saturationMatrix = mat4(
4344 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4345 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4346 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4347 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4348 );
4349 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4350 } else {
4351 colorMatrix = mClientColorMatrix * mDaltonizer();
4352 }
4353
4354 if (mCurrentState.colorMatrix != colorMatrix) {
4355 mCurrentState.colorMatrix = colorMatrix;
4356 mCurrentState.colorMatrixChanged = true;
4357 setTransactionFlags(eTransactionNeeded);
4358 }
4359}
4360
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004361status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004362 switch (code) {
4363 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004364 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004365 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004366 case CLEAR_ANIMATION_FRAME_STATS:
4367 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004368 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004369 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004370 case ENABLE_VSYNC_INJECTIONS:
4371 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004372 {
4373 // codes that require permission check
4374 IPCThreadState* ipc = IPCThreadState::self();
4375 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004376 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004377 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004378 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004379 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004380 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004381 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004382 break;
4383 }
Robert Carr1db73f62016-12-21 12:58:51 -08004384 /*
4385 * Calling setTransactionState is safe, because you need to have been
4386 * granted a reference to Client* and Handle* to do anything with it.
4387 *
4388 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4389 */
4390 case SET_TRANSACTION_STATE:
4391 case CREATE_SCOPED_CONNECTION:
4392 {
4393 return OK;
4394 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004395 case CAPTURE_SCREEN:
4396 {
4397 // codes that require permission check
4398 IPCThreadState* ipc = IPCThreadState::self();
4399 const int pid = ipc->getCallingPid();
4400 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004401 if ((uid != AID_GRAPHICS) &&
4402 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004403 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004404 return PERMISSION_DENIED;
4405 }
4406 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004407 }
chaviwa76b2712017-09-20 12:02:26 -07004408 case CAPTURE_LAYERS: {
4409 IPCThreadState* ipc = IPCThreadState::self();
4410 const int pid = ipc->getCallingPid();
4411 const int uid = ipc->getCallingUid();
4412 if ((uid != AID_GRAPHICS) &&
4413 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4414 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4415 return PERMISSION_DENIED;
4416 }
4417 break;
4418 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004419 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004420 return OK;
4421}
4422
4423status_t SurfaceFlinger::onTransact(
4424 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4425{
4426 status_t credentialCheck = CheckTransactCodeCredentials(code);
4427 if (credentialCheck != OK) {
4428 return credentialCheck;
4429 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004430
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004431 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4432 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004433 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004434 IPCThreadState* ipc = IPCThreadState::self();
4435 const int uid = ipc->getCallingUid();
4436 if (CC_UNLIKELY(uid != AID_SYSTEM
4437 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004438 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004439 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004440 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004441 return PERMISSION_DENIED;
4442 }
4443 int n;
4444 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004445 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004446 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004447 return NO_ERROR;
4448 case 1002: // SHOW_UPDATES
4449 n = data.readInt32();
4450 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004451 invalidateHwcGeometry();
4452 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004453 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004454 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004455 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004456 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004457 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004458 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004459 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004460 setTransactionFlags(
4461 eTransactionNeeded|
4462 eDisplayTransactionNeeded|
4463 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004464 return NO_ERROR;
4465 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004466 case 1006:{ // send empty update
4467 signalRefresh();
4468 return NO_ERROR;
4469 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004470 case 1008: // toggle use of hw composer
4471 n = data.readInt32();
4472 mDebugDisableHWC = n ? 1 : 0;
4473 invalidateHwcGeometry();
4474 repaintEverything();
4475 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004476 case 1009: // toggle use of transform hint
4477 n = data.readInt32();
4478 mDebugDisableTransformHint = n ? 1 : 0;
4479 invalidateHwcGeometry();
4480 repaintEverything();
4481 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004482 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004483 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004484 reply->writeInt32(0);
4485 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004486 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004487 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004488 return NO_ERROR;
4489 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004490 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004491 if (!display) {
4492 return NAME_NOT_FOUND;
4493 }
4494
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004495 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004496 return NO_ERROR;
4497 }
4498 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004499 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004500 // daltonize
4501 n = data.readInt32();
4502 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004503 case 1:
4504 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4505 break;
4506 case 2:
4507 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4508 break;
4509 case 3:
4510 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4511 break;
4512 default:
4513 mDaltonizer.setType(ColorBlindnessType::None);
4514 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004515 }
4516 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004517 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004518 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004519 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004520 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004521
4522 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004523 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004524 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004525 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004526 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004527 // apply a color matrix
4528 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004529 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004530 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004531 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004532 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004533 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004534 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004535 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004536 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004537 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004538 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004539
4540 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4541 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004542 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004543 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4544 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4545 }
4546
Chia-I Wu28f320b2018-05-03 11:02:56 -07004547 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004548 return NO_ERROR;
4549 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004550 // This is an experimental interface
4551 // Needs to be shifted to proper binder interface when we productize
4552 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004553 n = data.readInt32();
4554 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004555 return NO_ERROR;
4556 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004557 case 1017: {
4558 n = data.readInt32();
4559 mForceFullDamage = static_cast<bool>(n);
4560 return NO_ERROR;
4561 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004562 case 1018: { // Modify Choreographer's phase offset
4563 n = data.readInt32();
4564 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4565 return NO_ERROR;
4566 }
4567 case 1019: { // Modify SurfaceFlinger's phase offset
4568 n = data.readInt32();
4569 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4570 return NO_ERROR;
4571 }
Irvel468051e2016-06-13 16:44:44 -07004572 case 1020: { // Layer updates interceptor
4573 n = data.readInt32();
4574 if (n) {
4575 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004576 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004577 }
4578 else{
4579 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004580 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004581 }
4582 return NO_ERROR;
4583 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004584 case 1021: { // Disable HWC virtual displays
4585 n = data.readInt32();
4586 mUseHwcVirtualDisplays = !n;
4587 return NO_ERROR;
4588 }
Romain Guy0147a172017-06-01 13:53:56 -07004589 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004590 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004591 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004592
Chia-I Wu28f320b2018-05-03 11:02:56 -07004593 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004594 return NO_ERROR;
4595 }
Romain Guy54f154a2017-10-24 21:40:32 +01004596 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004597 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004598 invalidateHwcGeometry();
4599 repaintEverything();
4600 return NO_ERROR;
4601 }
4602 case 1024: { // Is wide color gamut rendering/color management supported?
4603 reply->writeBool(hasWideColorDisplay);
4604 return NO_ERROR;
4605 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004606 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004607 n = data.readInt32();
4608 if (n) {
4609 ALOGV("LayerTracing enabled");
4610 mTracing.enable();
4611 doTracing("tracing.enable");
4612 reply->writeInt32(NO_ERROR);
4613 } else {
4614 ALOGV("LayerTracing disabled");
4615 status_t err = mTracing.disable();
4616 reply->writeInt32(err);
4617 }
4618 return NO_ERROR;
4619 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004620 case 1026: { // Get layer tracing status
4621 reply->writeBool(mTracing.isEnabled());
4622 return NO_ERROR;
4623 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004624 // Is a DisplayColorSetting supported?
4625 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004626 const auto display = getDefaultDisplayDevice();
4627 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004628 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004629 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004630
4631 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4632 switch (setting) {
4633 case DisplayColorSetting::MANAGED:
4634 reply->writeBool(hasWideColorDisplay);
4635 break;
4636 case DisplayColorSetting::UNMANAGED:
4637 reply->writeBool(true);
4638 break;
4639 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004640 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004641 break;
4642 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004643 reply->writeBool(
4644 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004645 break;
4646 }
4647 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004648 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004649 // Is VrFlinger active?
4650 case 1028: {
4651 Mutex::Autolock _l(mStateLock);
4652 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4653 return NO_ERROR;
4654 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004655 }
4656 }
4657 return err;
4658}
4659
Steven Thomas6d8110b2017-08-31 18:24:21 -07004660void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004661 android_atomic_or(1, &mRepaintEverything);
4662 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004663}
4664
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004665// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4666class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004667public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004668 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4669 ~WindowDisconnector() {
4670 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004671 }
4672
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004673private:
4674 ANativeWindow* mWindow;
4675 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004676};
4677
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004678status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4679 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4680 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4681 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004682 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004683 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004684
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004685 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004686
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004687 const auto display = getDisplayDeviceLocked(displayToken);
4688 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004689
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004690 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004691
4692 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004693 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004694 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004695}
4696
4697status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004698 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004699 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004700 ATRACE_CALL();
4701
4702 class LayerRenderArea : public RenderArea {
4703 public:
Robert Carr578038f2018-03-09 12:25:24 -08004704 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4705 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004706 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004707 mLayer(layer),
4708 mCrop(crop),
4709 mFlinger(flinger),
4710 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004711 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004712 Rect getBounds() const override {
4713 const Layer::State& layerState(mLayer->getDrawingState());
4714 return Rect(layerState.active.w, layerState.active.h);
4715 }
4716 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4717 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4718 bool isSecure() const override { return false; }
4719 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004720 Rect getSourceCrop() const override {
4721 if (mCrop.isEmpty()) {
4722 return getBounds();
4723 } else {
4724 return mCrop;
4725 }
4726 }
Robert Carr578038f2018-03-09 12:25:24 -08004727 class ReparentForDrawing {
4728 public:
4729 const sp<Layer>& oldParent;
4730 const sp<Layer>& newParent;
4731
4732 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4733 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004734 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004735 }
Robert Carr15eae092018-03-23 13:43:53 -07004736 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004737 };
4738
4739 void render(std::function<void()> drawLayers) override {
4740 if (!mChildrenOnly) {
4741 mTransform = mLayer->getTransform().inverse();
4742 drawLayers();
4743 } else {
4744 Rect bounds = getBounds();
4745 screenshotParentLayer =
4746 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4747 bounds.getWidth(), bounds.getHeight(), 0);
4748
4749 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4750 drawLayers();
4751 }
4752 }
chaviwa76b2712017-09-20 12:02:26 -07004753
chaviwa76b2712017-09-20 12:02:26 -07004754 private:
chaviw7206d492017-11-10 16:16:12 -08004755 const sp<Layer> mLayer;
4756 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004757
4758 // In the "childrenOnly" case we reparent the children to a screenshot
4759 // layer which has no properties set and which does not draw.
4760 sp<ContainerLayer> screenshotParentLayer;
4761 Transform mTransform;
4762
4763 SurfaceFlinger* mFlinger;
4764 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004765 };
4766
4767 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4768 auto parent = layerHandle->owner.promote();
4769
chaviw7206d492017-11-10 16:16:12 -08004770 if (parent == nullptr || parent->isPendingRemoval()) {
4771 ALOGE("captureLayers called with a removed parent");
4772 return NAME_NOT_FOUND;
4773 }
4774
Robert Carr578038f2018-03-09 12:25:24 -08004775 const int uid = IPCThreadState::self()->getCallingUid();
4776 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4777 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4778 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4779 return PERMISSION_DENIED;
4780 }
4781
chaviw7206d492017-11-10 16:16:12 -08004782 Rect crop(sourceCrop);
4783 if (sourceCrop.width() <= 0) {
4784 crop.left = 0;
4785 crop.right = parent->getCurrentState().active.w;
4786 }
4787
4788 if (sourceCrop.height() <= 0) {
4789 crop.top = 0;
4790 crop.bottom = parent->getCurrentState().active.h;
4791 }
4792
4793 int32_t reqWidth = crop.width() * frameScale;
4794 int32_t reqHeight = crop.height() * frameScale;
4795
Robert Carr578038f2018-03-09 12:25:24 -08004796 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004797
Robert Carr578038f2018-03-09 12:25:24 -08004798 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004799 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4800 if (!layer->isVisible()) {
4801 return;
Robert Carr578038f2018-03-09 12:25:24 -08004802 } else if (childrenOnly && layer == parent.get()) {
4803 return;
chaviwa76b2712017-09-20 12:02:26 -07004804 }
4805 visitor(layer);
4806 });
4807 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004808 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004809}
4810
4811status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4812 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004813 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004814 bool useIdentityTransform) {
4815 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004816
Iris Chang7501ed62018-04-30 14:45:42 +08004817 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004818
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004819 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4820 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4821 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4822 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004823
4824 // This mutex protects syncFd and captureResult for communication of the return values from the
4825 // main thread back to this Binder thread
4826 std::mutex captureMutex;
4827 std::condition_variable captureCondition;
4828 std::unique_lock<std::mutex> captureLock(captureMutex);
4829 int syncFd = -1;
4830 std::optional<status_t> captureResult;
4831
Robert Carr03480e22018-01-04 16:02:06 -08004832 const int uid = IPCThreadState::self()->getCallingUid();
4833 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4834
Dominik Laskowski8c001672018-05-30 16:52:06 -07004835 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004836 // If there is a refresh pending, bug out early and tell the binder thread to try again
4837 // after the refresh.
4838 if (mRefreshPending) {
4839 ATRACE_NAME("Skipping screenshot for now");
4840 std::unique_lock<std::mutex> captureLock(captureMutex);
4841 captureResult = std::make_optional<status_t>(EAGAIN);
4842 captureCondition.notify_one();
4843 return;
4844 }
4845
4846 status_t result = NO_ERROR;
4847 int fd = -1;
4848 {
4849 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07004850 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08004851 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4852 useIdentityTransform, forSystem, &fd);
4853 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004854 }
4855
4856 {
4857 std::unique_lock<std::mutex> captureLock(captureMutex);
4858 syncFd = fd;
4859 captureResult = std::make_optional<status_t>(result);
4860 captureCondition.notify_one();
4861 }
4862 });
4863
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004864 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004865 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004866 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004867 while (*captureResult == EAGAIN) {
4868 captureResult.reset();
4869 result = postMessageAsync(message);
4870 if (result != NO_ERROR) {
4871 return result;
4872 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07004873 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004874 }
4875 result = *captureResult;
4876 }
4877
4878 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004879 sync_wait(syncFd, -1);
4880 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004881 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004882
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004883 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004884}
4885
chaviwa76b2712017-09-20 12:02:26 -07004886void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4887 TraverseLayersFunction traverseLayers, bool yswap,
4888 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004889 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004890
Lloyd Pique144e1162017-12-20 16:44:52 -08004891 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004892
4893 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004894 const auto raWidth = renderArea.getWidth();
4895 const auto raHeight = renderArea.getHeight();
4896
4897 const auto reqWidth = renderArea.getReqWidth();
4898 const auto reqHeight = renderArea.getReqHeight();
4899 Rect sourceCrop = renderArea.getSourceCrop();
4900
Iris Chang7501ed62018-04-30 14:45:42 +08004901 bool filtering = false;
4902 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4903 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
4904 static_cast<int32_t>(reqHeight) != raWidth;
4905 } else {
4906 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4907 static_cast<int32_t>(reqHeight) != raHeight;
4908 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004909
Dan Stozac1879002014-05-22 15:59:05 -07004910 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004911 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004912 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004913 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08004914 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4915 Transform tr;
4916 uint32_t flags = 0x00;
4917 switch (mPrimaryDisplayOrientation) {
4918 case DisplayState::eOrientation90:
4919 flags = Transform::ROT_90;
4920 break;
4921 case DisplayState::eOrientation180:
4922 flags = Transform::ROT_180;
4923 break;
4924 case DisplayState::eOrientation270:
4925 flags = Transform::ROT_270;
4926 break;
4927 }
4928 tr.set(flags, raWidth, raHeight);
4929 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07004930 }
4931
4932 // ensure that sourceCrop is inside screen
4933 if (sourceCrop.left < 0) {
4934 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4935 }
chaviwa76b2712017-09-20 12:02:26 -07004936 if (sourceCrop.right > raWidth) {
4937 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004938 }
4939 if (sourceCrop.top < 0) {
4940 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4941 }
chaviwa76b2712017-09-20 12:02:26 -07004942 if (sourceCrop.bottom > raHeight) {
4943 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004944 }
4945
Chia-I Wu36574d92018-05-16 10:54:36 -07004946 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
4947 engine.setOutputDataSpace(Dataspace::SRGB);
4948 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07004949
Mathias Agopian180f10d2013-04-10 22:55:41 -07004950 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004951 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004952
Iris Chang7501ed62018-04-30 14:45:42 +08004953 Transform::orientation_flags rotation = renderArea.getRotationFlags();
4954 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4955 // convert hw orientation into flag presentation
4956 // here inverse transform needed
4957 uint8_t hw_rot_90 = 0x00;
4958 uint8_t hw_flip_hv = 0x00;
4959 switch (mPrimaryDisplayOrientation) {
4960 case DisplayState::eOrientation90:
4961 hw_rot_90 = Transform::ROT_90;
4962 hw_flip_hv = Transform::ROT_180;
4963 break;
4964 case DisplayState::eOrientation180:
4965 hw_flip_hv = Transform::ROT_180;
4966 break;
4967 case DisplayState::eOrientation270:
4968 hw_rot_90 = Transform::ROT_90;
4969 break;
4970 }
4971
4972 // transform flags operation
4973 // 1) flip H V if both have ROT_90 flag
4974 // 2) XOR these flags
4975 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
4976 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
4977 if (rotation_rot_90 & hw_rot_90) {
4978 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
4979 }
4980 rotation = static_cast<Transform::orientation_flags>
4981 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
4982 }
4983
Mathias Agopian180f10d2013-04-10 22:55:41 -07004984 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004985 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08004986 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004987 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004988
chaviw50da5042018-04-09 13:49:37 -07004989 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004990 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004991 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004992
chaviwa76b2712017-09-20 12:02:26 -07004993 traverseLayers([&](Layer* layer) {
4994 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07004995 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004996 if (filtering) layer->setFiltering(false);
4997 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004998}
4999
chaviwa76b2712017-09-20 12:02:26 -07005000status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5001 TraverseLayersFunction traverseLayers,
5002 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005003 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005004 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005005 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005006 ATRACE_CALL();
5007
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005008 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005009
5010 traverseLayers([&](Layer* layer) {
5011 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5012 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005013
Robert Carr03480e22018-01-04 16:02:06 -08005014 // We allow the system server to take screenshots of secure layers for
5015 // use in situations like the Screen-rotation animation and place
5016 // the impetus on WindowManager to not persist them.
5017 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005018 ALOGW("FB is protected: PERMISSION_DENIED");
5019 return PERMISSION_DENIED;
5020 }
5021
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005022 // this binds the given EGLImage as a framebuffer for the
5023 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005024 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005025 if (bufferBond.getStatus() != NO_ERROR) {
5026 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005027 return INVALID_OPERATION;
5028 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005029
Dan Stozaabcda352017-06-01 14:37:39 -07005030 // this will in fact render into our dequeued buffer
5031 // via an FBO, which means we didn't have to create
5032 // an EGLSurface and therefore we're not
5033 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005034 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005035
Dan Stozaabcda352017-06-01 14:37:39 -07005036 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005037 getRenderEngine().finish();
5038 *outSyncFd = -1;
5039
chaviwa76b2712017-09-20 12:02:26 -07005040 const auto reqWidth = renderArea.getReqWidth();
5041 const auto reqHeight = renderArea.getReqHeight();
5042
Dan Stozaabcda352017-06-01 14:37:39 -07005043 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5044 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005045 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005046 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005047 } else {
5048 base::unique_fd syncFd = getRenderEngine().flush();
5049 if (syncFd < 0) {
5050 getRenderEngine().finish();
5051 }
5052 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005053 }
5054
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005055 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005056}
5057
Mathias Agopiand5556842013-09-19 17:08:37 -07005058void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005059 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005060 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005061 for (size_t y = 0; y < h; y++) {
5062 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5063 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005064 if (p[x] != 0xFF000000) return;
5065 }
5066 }
chaviwa76b2712017-09-20 12:02:26 -07005067 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005068
Robert Carr2047fae2016-11-28 14:09:09 -08005069 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005070 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005071 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005072 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5073 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5074 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5075 static_cast<float>(state.color.a));
5076 i++;
5077 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005078 }
5079}
5080
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005081// ---------------------------------------------------------------------------
5082
Dan Stoza412903f2017-04-27 13:42:17 -07005083void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5084 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005085}
5086
Dan Stoza412903f2017-04-27 13:42:17 -07005087void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5088 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005089}
5090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005091void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5092 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005093 const LayerVector::Visitor& visitor) {
5094 // We loop through the first level of layers without traversing,
5095 // as we need to interpret min/max layer Z in the top level Z space.
5096 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005097 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005098 continue;
5099 }
5100 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005101 // relative layers are traversed in Layer::traverseInZOrder
5102 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005103 continue;
5104 }
5105 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005106 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005107 return;
5108 }
chaviwa76b2712017-09-20 12:02:26 -07005109 if (!layer->isVisible()) {
5110 return;
5111 }
5112 visitor(layer);
5113 });
5114 }
5115}
5116
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005117}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005118
Chia-I Wu30505fb2018-03-26 16:20:31 -07005119
Mathias Agopian3f844832013-08-07 21:24:32 -07005120#if defined(__gl_h_)
5121#error "don't include gl/gl.h in this file"
5122#endif
5123
5124#if defined(__gl2_h_)
5125#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005126#endif