blob: 32c313be7855a4866cf54b5202af282e24a2fd1e [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include "Effects/Daltonizer.h"
87
Mathias Agopian875d8e12013-06-07 15:35:48 -070088#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070089#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070090
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080092#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
93#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090094#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090095
chaviw1d044282017-09-27 12:19:28 -070096#include <layerproto/LayerProtoParser.h>
97
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080098#define DISPLAY_COUNT 1
99
Mathias Agopianfee2b462013-07-03 12:34:01 -0700100/*
101 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
102 * black pixels.
103 */
104#define DEBUG_SCREENSHOTS false
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107
Jaesoo Lee43518572017-01-23 19:03:16 +0900108using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700110using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700111using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700112using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700113using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
Steven Thomasb02664d2017-07-26 18:48:28 -0700115namespace {
116class ConditionalLock {
117public:
118 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
119 if (lock) {
120 mMutex.lock();
121 }
122 }
123 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
124private:
125 Mutex& mMutex;
126 bool mLocked;
127};
128} // namespace anonymous
129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130// ---------------------------------------------------------------------------
131
Mathias Agopian99b49842011-06-27 16:05:52 -0700132const String16 sHardwareTest("android.permission.HARDWARE_TEST");
133const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
134const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
135const String16 sDump("android.permission.DUMP");
136
137// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800138int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
139int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700140int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700141bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800142uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800143bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800144bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800145int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800146// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600147bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700148
Kalle Raitaa099a242017-01-11 11:17:29 -0800149
150std::string getHwcServiceName() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.hwc_service_name", value, "default");
153 ALOGI("Using HWComposer service: '%s'", value);
154 return std::string(value);
155}
156
157bool useTrebleTestingOverride() {
158 char value[PROPERTY_VALUE_MAX] = {};
159 property_get("debug.sf.treble_testing_override", value, "false");
160 ALOGI("Treble testing override: '%s'", value);
161 return std::string(value) == "true";
162}
163
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800164std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
165 switch(displayColorSetting) {
166 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700167 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800168 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700169 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800170 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700171 return std::string("Enhanced");
172 default:
173 return std::string("Unknown ") +
174 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800175 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800176}
177
Lloyd Pique99d3da52018-01-22 17:48:03 -0800178NativeWindowSurface::~NativeWindowSurface() = default;
179
180namespace impl {
181
182class NativeWindowSurface final : public android::NativeWindowSurface {
183public:
184 static std::unique_ptr<android::NativeWindowSurface> create(
185 const sp<IGraphicBufferProducer>& producer) {
186 return std::make_unique<NativeWindowSurface>(producer);
187 }
188
189 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
190 : surface(new Surface(producer, false)) {}
191
192 ~NativeWindowSurface() override = default;
193
194private:
195 sp<ANativeWindow> getNativeWindow() const override { return surface; }
196
197 void preallocateBuffers() override { surface->allocateBuffers(); }
198
199 sp<Surface> surface;
200};
201
202} // namespace impl
203
David Sodmanbc815282017-11-05 18:57:52 -0800204SurfaceFlingerBE::SurfaceFlingerBE()
205 : mHwcServiceName(getHwcServiceName()),
206 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800207 mFrameBuckets(),
208 mTotalTime(0),
209 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800210 mComposerSequenceId(0) {
211}
212
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800213SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800214 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800215 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700216 mTransactionPending(false),
217 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700218 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700219 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700220 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800221 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700222 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800224 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800225 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700227 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700228 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700229 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700230 mDebugInSwapBuffers(0),
231 mLastSwapBufferTime(0),
232 mDebugInTransaction(0),
233 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700234 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700235 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000236 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700237 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700238 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800239 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800240 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700241 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800242 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800243 mCreateBufferQueue(&BufferQueue::createBufferQueue),
244 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800245
246SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800247 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800248
249 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
250 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
251
252 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
253 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
254
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800255 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
256 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700258 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
259 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
260
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700261 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
262 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
263
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800264 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
265 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
266
Steven Thomas050b2c82017-03-06 11:45:16 -0800267 // Vr flinger is only enabled on Daydream ready devices.
268 useVrFlinger = getBool< ISurfaceFlingerConfigs,
269 &ISurfaceFlingerConfigs::useVrFlinger>(false);
270
Fabien Sanglard1971b632017-03-10 14:50:03 -0800271 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
272 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
273
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600274 hasWideColorDisplay =
275 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
276
Iris Chang7501ed62018-04-30 14:45:42 +0800277 V1_1::DisplayOrientation primaryDisplayOrientation =
278 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
279 V1_1::DisplayOrientation::ORIENTATION_0);
280
281 switch (primaryDisplayOrientation) {
282 case V1_1::DisplayOrientation::ORIENTATION_90:
283 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
284 break;
285 case V1_1::DisplayOrientation::ORIENTATION_180:
286 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
287 break;
288 case V1_1::DisplayOrientation::ORIENTATION_270:
289 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
290 break;
291 default:
292 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
293 break;
294 }
295 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
296
David Sodman99974d22017-11-28 12:04:33 -0800297 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700298
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299 // debugging stuff...
300 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700301
Mathias Agopianb4b17302013-03-20 18:36:41 -0700302 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700303 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700304
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 property_get("debug.sf.showupdates", value, "0");
306 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700307
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700308 property_get("debug.sf.ddms", value, "0");
309 mDebugDDMS = atoi(value);
310 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700311 if (!startDdmConnection()) {
312 // start failed, and DDMS debugging not enabled
313 mDebugDDMS = 0;
314 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700315 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700316 ALOGI_IF(mDebugRegion, "showupdates enabled");
317 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700318
319 property_get("debug.sf.disable_backpressure", value, "0");
320 mPropagateBackpressure = !atoi(value);
321 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700322
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800323 property_get("debug.sf.enable_hwc_vds", value, "0");
324 mUseHwcVirtualDisplays = atoi(value);
325 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800326
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800327 property_get("ro.sf.disable_triple_buffer", value, "1");
328 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800329 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700330
Yiwei Zhang243b3782018-05-15 17:40:04 -0700331 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700332 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
333 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
334
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200335 property_get("debug.sf.early_phase_offset_ns", value, "-1");
336 const int earlySfOffsetNs = atoi(value);
337
338 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
339 const int earlyGlSfOffsetNs = atoi(value);
340
341 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
342 const int earlyAppOffsetNs = atoi(value);
343
344 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
345 const int earlyGlAppOffsetNs = atoi(value);
346
347 const VSyncModulator::Offsets earlyOffsets =
348 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
349 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
350 const VSyncModulator::Offsets earlyGlOffsets =
351 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
352 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
353 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
354 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700355
Romain Guy11d63f42017-07-20 12:47:14 -0700356 // We should be reading 'persist.sys.sf.color_saturation' here
357 // but since /data may be encrypted, we need to wait until after vold
358 // comes online to attempt to read the property. The property is
359 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800360
361 if (useTrebleTestingOverride()) {
362 // Without the override SurfaceFlinger cannot connect to HIDL
363 // services that are not listed in the manifests. Considered
364 // deriving the setting from the set service name, but it
365 // would be brittle if the name that's not 'default' is used
366 // for production purposes later on.
367 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
368 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800369}
370
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800371void SurfaceFlinger::onFirstRef()
372{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800373 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800374}
375
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376SurfaceFlinger::~SurfaceFlinger()
377{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378}
379
Dan Stozac7014012014-02-14 15:03:43 -0800380void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800381{
382 // the window manager died on us. prepare its eulogy.
383
Andy McFadden13a082e2012-08-24 10:16:42 -0700384 // restore initial conditions (default device unblank, etc)
385 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800386
387 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700388 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800389}
390
Robert Carr1db73f62016-12-21 12:58:51 -0800391static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700392 status_t err = client->initCheck();
393 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800394 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800395 }
Robert Carr1db73f62016-12-21 12:58:51 -0800396 return nullptr;
397}
398
399sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
400 return initClient(new Client(this));
401}
402
403sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
404 const sp<IGraphicBufferProducer>& gbp) {
405 if (authenticateSurfaceTexture(gbp) == false) {
406 return nullptr;
407 }
408 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
409 if (layer == nullptr) {
410 return nullptr;
411 }
412
413 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414}
415
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700416sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
417 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700418{
419 class DisplayToken : public BBinder {
420 sp<SurfaceFlinger> flinger;
421 virtual ~DisplayToken() {
422 // no more references, this display must be terminated
423 Mutex::Autolock _l(flinger->mStateLock);
424 flinger->mCurrentState.displays.removeItem(this);
425 flinger->setTransactionFlags(eDisplayTransactionNeeded);
426 }
427 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700428 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700429 : flinger(flinger) {
430 }
431 };
432
433 sp<BBinder> token = new DisplayToken(this);
434
435 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700436 DisplayDeviceState info;
437 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700438 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700439 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800441 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700442 return token;
443}
444
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700445void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700446 Mutex::Autolock _l(mStateLock);
447
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700448 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700449 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700450 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700451 return;
452 }
453
454 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700455 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700456 ALOGE("destroyDisplay called for non-virtual display");
457 return;
458 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700459 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700460 mCurrentState.displays.removeItemsAt(idx);
461 setTransactionFlags(eDisplayTransactionNeeded);
462}
463
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700465 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700466 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800467 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700468 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700469 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470}
471
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800472void SurfaceFlinger::bootFinished()
473{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700474 if (mStartPropertySetThread->join() != NO_ERROR) {
475 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800476 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800477 const nsecs_t now = systemTime();
478 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000479 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700480
481 // wait patiently for the window manager death
482 const String16 name("window");
483 sp<IBinder> window(defaultServiceManager()->getService(name));
484 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700485 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700486 }
487
Steven Thomas050b2c82017-03-06 11:45:16 -0800488 if (mVrFlinger) {
489 mVrFlinger->OnBootFinished();
490 }
491
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700492 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700493 // formerly we would just kill the process, but we now ask it to exit so it
494 // can choose where to stop the animation.
495 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700496
497 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
498 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
499 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700500
Dominik Laskowski8c001672018-05-30 16:52:06 -0700501 postMessageAsync(new LambdaMessage([this] { readPersistentProperties(); }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800502}
503
Dan Stoza436ccf32018-06-21 12:10:12 -0700504uint32_t SurfaceFlinger::getNewTexture() {
505 {
506 std::lock_guard lock(mTexturePoolMutex);
507 if (!mTexturePool.empty()) {
508 uint32_t name = mTexturePool.back();
509 mTexturePool.pop_back();
510 ATRACE_INT("TexturePoolSize", mTexturePool.size());
511 return name;
512 }
513
514 // The pool was too small, so increase it for the future
515 ++mTexturePoolSize;
516 }
517
518 // The pool was empty, so we need to get a new texture name directly using a
519 // blocking call to the main thread
520 uint32_t name = 0;
521 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
522 return name;
523}
524
Mathias Agopian3f844832013-08-07 21:24:32 -0700525void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700526 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700527}
528
Lloyd Piquee83f9312018-02-01 12:53:17 -0800529class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700531 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000532 const char* name) :
533 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700534 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700535 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000536 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
537 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700538 mDispSync(dispSync),
539 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700540 mVsyncMutex(),
541 mPhaseOffset(phaseOffset),
542 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700543
Lloyd Piquee83f9312018-02-01 12:53:17 -0800544 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700545
Lloyd Piquee83f9312018-02-01 12:53:17 -0800546 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700547 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700548 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000549 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700550 static_cast<DispSync::Callback*>(this));
551 if (err != NO_ERROR) {
552 ALOGE("error registering vsync callback: %s (%d)",
553 strerror(-err), err);
554 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700555 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700556 } else {
557 status_t err = mDispSync->removeEventListener(
558 static_cast<DispSync::Callback*>(this));
559 if (err != NO_ERROR) {
560 ALOGE("error unregistering vsync callback: %s (%d)",
561 strerror(-err), err);
562 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700563 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700564 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700565 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700566 }
567
Lloyd Piquee83f9312018-02-01 12:53:17 -0800568 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700569 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700570 mCallback = callback;
571 }
572
Lloyd Piquee83f9312018-02-01 12:53:17 -0800573 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700574 Mutex::Autolock lock(mVsyncMutex);
575
576 // Normalize phaseOffset to [0, period)
577 auto period = mDispSync->getPeriod();
578 phaseOffset %= period;
579 if (phaseOffset < 0) {
580 // If we're here, then phaseOffset is in (-period, 0). After this
581 // operation, it will be in (0, period)
582 phaseOffset += period;
583 }
584 mPhaseOffset = phaseOffset;
585
586 // If we're not enabled, we don't need to mess with the listeners
587 if (!mEnabled) {
588 return;
589 }
590
Dan Stoza84d619e2018-03-28 17:07:36 -0700591 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
592 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700593 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700594 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700595 strerror(-err), err);
596 }
597 }
598
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700599private:
600 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800601 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700603 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604 callback = mCallback;
605
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700606 if (mTraceVsync) {
607 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700608 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700609 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700610 }
611
Peiyong Lin566a3b42018-01-09 18:22:43 -0800612 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700613 callback->onVSyncEvent(when);
614 }
615 }
616
Tim Murray4a4e4a22016-04-19 16:29:23 +0000617 const char* const mName;
618
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700619 int mValue;
620
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700621 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700622 const String8 mVsyncOnLabel;
623 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700624
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700625 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700626
627 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800628 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700629
630 Mutex mVsyncMutex; // Protects the following
631 nsecs_t mPhaseOffset;
632 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700633};
634
Lloyd Piquee83f9312018-02-01 12:53:17 -0800635class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700636public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800637 InjectVSyncSource() = default;
638 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700639
Lloyd Piquee83f9312018-02-01 12:53:17 -0800640 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700641 std::lock_guard<std::mutex> lock(mCallbackMutex);
642 mCallback = callback;
643 }
644
Lloyd Piquee83f9312018-02-01 12:53:17 -0800645 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700646 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700647 if (mCallback) {
648 mCallback->onVSyncEvent(when);
649 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700650 }
651
Lloyd Piquee83f9312018-02-01 12:53:17 -0800652 void setVSyncEnabled(bool) override {}
653 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700654
655private:
656 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800657 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700658};
659
Wei Wangf9b05ee2017-07-19 20:59:39 -0700660// Do not call property_set on main thread which will be blocked by init
661// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700662void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700663 ALOGI( "SurfaceFlinger's main thread ready to run. "
664 "Initializing graphics H/W...");
665
Thierry Strudel2924d012017-08-14 15:19:37 -0700666 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900667
Steven Thomasb02664d2017-07-26 18:48:28 -0700668 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800669
Steven Thomasb02664d2017-07-26 18:48:28 -0700670 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800671 mEventThreadSource =
672 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
673 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800674 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700675 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800676 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800677 "appEventThread");
678 mSfEventThreadSource =
679 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
680 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800681
Lloyd Pique24b0a482018-03-09 18:52:26 -0800682 mSFEventThread =
683 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700684 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800685 [this](nsecs_t timestamp) {
686 mInterceptor->saveVSyncEvent(timestamp);
687 },
688 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800689 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200690 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800691
Steven Thomasb02664d2017-07-26 18:48:28 -0700692 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800693 getBE().mRenderEngine =
694 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
695 hasWideColorDisplay
696 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
697 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800698 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700699
700 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
701 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800702 getBE().mHwc.reset(
703 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700704 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800705 // Process any initial hotplug and resulting display changes.
706 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700707 const auto display = getDefaultDisplayDeviceLocked();
708 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
709 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
710 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800711
Lloyd Piquefcd86612017-12-14 17:15:36 -0800712 // make the default display GLContext current so that we can create textures
713 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700714 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800715
Steven Thomas050b2c82017-03-06 11:45:16 -0800716 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700717 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700718 // This callback is called from the vr flinger dispatch thread. We
719 // need to call signalTransaction(), which requires holding
720 // mStateLock when we're not on the main thread. Acquiring
721 // mStateLock from the vr flinger dispatch thread might trigger a
722 // deadlock in surface flinger (see b/66916578), so post a message
723 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700724 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700725 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
726 mVrFlingerRequestsDisplay = requestDisplay;
727 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700728 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800729 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700730 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
731 getHwComposer()
732 .getHwcDisplayId(display->getId())
733 .value_or(0),
734 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800735 if (!mVrFlinger) {
736 ALOGE("Failed to start vrflinger");
737 }
738 }
739
Lloyd Pique379adc12018-01-22 17:31:47 -0800740 mEventControlThread = std::make_unique<impl::EventControlThread>(
741 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700742
Mathias Agopian92a979a2012-08-02 18:32:23 -0700743 // initialize our drawing state
744 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700745
Andy McFadden13a082e2012-08-24 10:16:42 -0700746 // set initial conditions (e.g. unblank default device)
747 initializeDisplays();
748
David Sodmanbc815282017-11-05 18:57:52 -0800749 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700750
Wei Wangf9b05ee2017-07-19 20:59:39 -0700751 // Inform native graphics APIs whether the present timestamp is supported:
752 if (getHwComposer().hasCapability(
753 HWC2::Capability::PresentFenceIsNotReliable)) {
754 mStartPropertySetThread = new StartPropertySetThread(false);
755 } else {
756 mStartPropertySetThread = new StartPropertySetThread(true);
757 }
758
759 if (mStartPropertySetThread->Start() != NO_ERROR) {
760 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800761 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800762
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700763 mLegacySrgbSaturationMatrix =
764 getHwComposer().getDataspaceSaturationMatrix(display->getId(), Dataspace::SRGB_LINEAR);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800765
Dan Stoza9e56aa02015-11-02 13:00:03 -0800766 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700767}
768
Romain Guy11d63f42017-07-20 12:47:14 -0700769void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700770 Mutex::Autolock _l(mStateLock);
771
Romain Guy11d63f42017-07-20 12:47:14 -0700772 char value[PROPERTY_VALUE_MAX];
773
774 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800775 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700776 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800777 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100778
779 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700780 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700781}
782
Mathias Agopiana67e4182012-06-19 17:26:12 -0700783void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800784 // Start boot animation service by setting a property mailbox
785 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700786 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800787 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700788 if (mStartPropertySetThread->join() != NO_ERROR) {
789 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800790 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700791}
792
Mathias Agopian875d8e12013-06-07 15:35:48 -0700793size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800794 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700795}
796
Mathias Agopian875d8e12013-06-07 15:35:48 -0700797size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800798 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700799}
800
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800801// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800802
Jamie Gennis582270d2011-08-17 18:19:00 -0700803bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800804 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800805 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800806 return authenticateSurfaceTextureLocked(bufferProducer);
807}
808
809bool SurfaceFlinger::authenticateSurfaceTextureLocked(
810 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800811 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800812 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800813}
814
Brian Anderson6b376712017-04-04 10:51:39 -0700815status_t SurfaceFlinger::getSupportedFrameTimestamps(
816 std::vector<FrameEvent>* outSupported) const {
817 *outSupported = {
818 FrameEvent::REQUESTED_PRESENT,
819 FrameEvent::ACQUIRE,
820 FrameEvent::LATCH,
821 FrameEvent::FIRST_REFRESH_START,
822 FrameEvent::LAST_REFRESH_START,
823 FrameEvent::GPU_COMPOSITION_DONE,
824 FrameEvent::DEQUEUE_READY,
825 FrameEvent::RELEASE,
826 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700827 ConditionalLock _l(mStateLock,
828 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700829 if (!getHwComposer().hasCapability(
830 HWC2::Capability::PresentFenceIsNotReliable)) {
831 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
832 }
833 return NO_ERROR;
834}
835
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700836status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
837 Vector<DisplayInfo>* configs) {
838 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 return BAD_VALUE;
840 }
841
Jesse Hall692c7232012-11-08 15:41:56 -0800842 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700843 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
844 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700845 type = i;
846 break;
847 }
848 }
849
850 if (type < 0) {
851 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700852 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700853
Mathias Agopian8b736f12012-08-13 17:54:26 -0700854 // TODO: Not sure if display density should handled by SF any longer
855 class Density {
856 static int getDensityFromProperty(char const* propName) {
857 char property[PROPERTY_VALUE_MAX];
858 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800859 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700860 density = atoi(property);
861 }
862 return density;
863 }
864 public:
865 static int getEmuDensity() {
866 return getDensityFromProperty("qemu.sf.lcd_density"); }
867 static int getBuildDensity() {
868 return getDensityFromProperty("ro.sf.lcd_density"); }
869 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700870
Dan Stoza7f7da322014-05-02 15:26:25 -0700871 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700872
Steven Thomas6d8110b2017-08-31 18:24:21 -0700873 ConditionalLock _l(mStateLock,
874 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800875 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700876 DisplayInfo info = DisplayInfo();
877
Dan Stoza9e56aa02015-11-02 13:00:03 -0800878 float xdpi = hwConfig->getDpiX();
879 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700880
881 if (type == DisplayDevice::DISPLAY_PRIMARY) {
882 // The density of the device is provided by a build property
883 float density = Density::getBuildDensity() / 160.0f;
884 if (density == 0) {
885 // the build doesn't provide a density -- this is wrong!
886 // use xdpi instead
887 ALOGE("ro.sf.lcd_density must be defined as a build property");
888 density = xdpi / 160.0f;
889 }
890 if (Density::getEmuDensity()) {
891 // if "qemu.sf.lcd_density" is specified, it overrides everything
892 xdpi = ydpi = density = Density::getEmuDensity();
893 density /= 160.0f;
894 }
895 info.density = density;
896
897 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700898 const auto display = getDefaultDisplayDeviceLocked();
899 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700900 } else {
901 // TODO: where should this value come from?
902 static const int TV_DENSITY = 213;
903 info.density = TV_DENSITY / 160.0f;
904 info.orientation = 0;
905 }
906
Dan Stoza9e56aa02015-11-02 13:00:03 -0800907 info.w = hwConfig->getWidth();
908 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700909 info.xdpi = xdpi;
910 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800911 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900912 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800913
Andy McFadden91b2ca82014-06-13 14:04:23 -0700914 // This is how far in advance a buffer must be queued for
915 // presentation at a given time. If you want a buffer to appear
916 // on the screen at time N, you must submit the buffer before
917 // (N - presentationDeadline).
918 //
919 // Normally it's one full refresh period (to give SF a chance to
920 // latch the buffer), but this can be reduced by configuring a
921 // DispSync offset. Any additional delays introduced by the hardware
922 // composer or panel must be accounted for here.
923 //
924 // We add an additional 1ms to allow for processing time and
925 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800926 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800927 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700928
929 // All non-virtual displays are currently considered secure.
930 info.secure = true;
931
Iris Chang7501ed62018-04-30 14:45:42 +0800932 if (type == DisplayDevice::DISPLAY_PRIMARY &&
933 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
934 std::swap(info.w, info.h);
935 }
936
Michael Wright28f24d02016-07-12 13:30:53 -0700937 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700938 }
939
Dan Stoza7f7da322014-05-02 15:26:25 -0700940 return NO_ERROR;
941}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
944 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700945 return BAD_VALUE;
946 }
947
948 // FIXME for now we always return stats for the primary display
949 memset(stats, 0, sizeof(*stats));
950 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
951 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
952 return NO_ERROR;
953}
954
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700955int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
956 const auto display = getDisplayDevice(displayToken);
957 if (!display) {
958 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800959 return BAD_VALUE;
960 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700961
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700963}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700964
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700965void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
966 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700967 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700968 return;
969 }
970
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700971 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700972 ALOGW("Trying to set config for virtual display");
973 return;
974 }
975
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700976 display->setActiveConfig(mode);
977 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700978}
979
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700980status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700981 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700982 Vector<DisplayInfo> configs;
983 getDisplayConfigs(displayToken, &configs);
984 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
985 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
986 configs.size());
987 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700988 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700989 const auto display = getDisplayDevice(displayToken);
990 if (!display) {
991 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
992 displayToken.get());
993 } else if (display->isVirtual()) {
994 ALOGW("Attempt to set active config %d for virtual display", mode);
995 } else {
996 setActiveConfigInternal(display, mode);
997 }
998 }));
999
Mathias Agopian888c8222012-08-04 21:10:38 -07001000 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001001}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001002status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1003 Vector<ColorMode>* outColorModes) {
1004 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001005 return BAD_VALUE;
1006 }
1007
Michael Wright28f24d02016-07-12 13:30:53 -07001008 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1010 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001011 type = i;
1012 break;
1013 }
1014 }
1015
1016 if (type < 0) {
1017 return type;
1018 }
1019
Peiyong Lina52f0292018-03-14 17:26:31 -07001020 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001021 {
1022 ConditionalLock _l(mStateLock,
1023 std::this_thread::get_id() != mMainThreadId);
1024 modes = getHwComposer().getColorModes(type);
1025 }
Michael Wright28f24d02016-07-12 13:30:53 -07001026 outColorModes->clear();
1027 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1028
1029 return NO_ERROR;
1030}
1031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1033 if (const auto display = getDisplayDevice(displayToken)) {
1034 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001035 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001036 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001037}
1038
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001039void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1040 Dataspace dataSpace, RenderIntent renderIntent) {
1041 ColorMode currentMode = display->getActiveColorMode();
1042 Dataspace currentDataSpace = display->getCompositionDataSpace();
1043 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001044
Peiyong Lin38e9a562018-04-10 16:24:20 -07001045 if (mode == currentMode && dataSpace == currentDataSpace &&
1046 renderIntent == currentRenderIntent) {
1047 return;
1048 }
1049
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001051 ALOGW("Trying to set config for virtual display");
1052 return;
1053 }
1054
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055 display->setActiveColorMode(mode);
1056 display->setCompositionDataSpace(dataSpace);
1057 display->setActiveRenderIntent(renderIntent);
1058 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001059
1060 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001061 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1062 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001063}
1064
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001065status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001066 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001067 Vector<ColorMode> modes;
1068 getDisplayColorModes(displayToken, &modes);
1069 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1070 if (mode < ColorMode::NATIVE || !exists) {
1071 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1072 decodeColorMode(mode).c_str(), mode, displayToken.get());
1073 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001074 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001075 const auto display = getDisplayDevice(displayToken);
1076 if (!display) {
1077 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1078 decodeColorMode(mode).c_str(), mode, displayToken.get());
1079 } else if (display->isVirtual()) {
1080 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1081 decodeColorMode(mode).c_str(), mode);
1082 } else {
1083 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1084 RenderIntent::COLORIMETRIC);
1085 }
1086 }));
1087
Michael Wright28f24d02016-07-12 13:30:53 -07001088 return NO_ERROR;
1089}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001090
Svetoslavd85084b2014-03-20 10:28:31 -07001091status_t SurfaceFlinger::clearAnimationFrameStats() {
1092 Mutex::Autolock _l(mStateLock);
1093 mAnimFrameTracker.clearStats();
1094 return NO_ERROR;
1095}
1096
1097status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1098 Mutex::Autolock _l(mStateLock);
1099 mAnimFrameTracker.getStats(outStats);
1100 return NO_ERROR;
1101}
1102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1104 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001105 Mutex::Autolock _l(mStateLock);
1106
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001107 const auto display = getDisplayDeviceLocked(displayToken);
1108 if (!display) {
1109 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001110 return BAD_VALUE;
1111 }
1112
Peiyong Linfb069302018-04-25 14:34:31 -07001113 // At this point the DisplayDeivce should already be set up,
1114 // meaning the luminance information is already queried from
1115 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001116 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001117 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1118 capabilities.getDesiredMaxLuminance(),
1119 capabilities.getDesiredMaxAverageLuminance(),
1120 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001121
1122 return NO_ERROR;
1123}
1124
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001125status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001126 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001127 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001128
Chia-I Wu90f669f2017-10-05 14:24:41 -07001129 if (mInjectVSyncs == enable) {
1130 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001131 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001132
1133 if (enable) {
1134 ALOGV("VSync Injections enabled");
1135 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001136 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001137 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001138 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001139 impl::EventThread::InterceptVSyncsCallback(),
1140 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001141 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001142 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001143 } else {
1144 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001145 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001146 }
1147
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001148 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001149 }));
1150
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001151 return NO_ERROR;
1152}
1153
1154status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001155 Mutex::Autolock _l(mStateLock);
1156
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001157 if (!mInjectVSyncs) {
1158 ALOGE("VSync Injections not enabled");
1159 return BAD_VALUE;
1160 }
1161 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1162 ALOGV("Injecting VSync inside SurfaceFlinger");
1163 mVSyncInjector->onInjectSyncEvent(when);
1164 }
1165 return NO_ERROR;
1166}
1167
Lloyd Pique755e3192018-01-31 16:46:15 -08001168status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1169 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001170 IPCThreadState* ipc = IPCThreadState::self();
1171 const int pid = ipc->getCallingPid();
1172 const int uid = ipc->getCallingUid();
1173 if ((uid != AID_SHELL) &&
1174 !PermissionCache::checkPermission(sDump, pid, uid)) {
1175 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1176 return PERMISSION_DENIED;
1177 }
1178
1179 // Try to acquire a lock for 1s, fail gracefully
1180 const status_t err = mStateLock.timedLock(s2ns(1));
1181 const bool locked = (err == NO_ERROR);
1182 if (!locked) {
1183 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1184 return TIMED_OUT;
1185 }
1186
1187 outLayers->clear();
1188 mCurrentState.traverseInZOrder([&](Layer* layer) {
1189 outLayers->push_back(layer->getLayerDebugInfo());
1190 });
1191
1192 mStateLock.unlock();
1193 return NO_ERROR;
1194}
1195
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001196// ----------------------------------------------------------------------------
1197
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001198sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1199 ISurfaceComposer::VsyncSource vsyncSource) {
1200 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1201 return mSFEventThread->createEventConnection();
1202 } else {
1203 return mEventThread->createEventConnection();
1204 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001205}
1206
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001207// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001208
1209void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001210 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001211}
1212
1213void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001214 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001215}
1216
1217void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001218 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001219}
1220
1221void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001222 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001223 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001224}
1225
1226status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001227 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001228 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229}
1230
1231status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001232 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001233 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234 if (res == NO_ERROR) {
1235 msg->wait();
1236 }
1237 return res;
1238}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001239
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001240void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001241 do {
1242 waitForEvent();
1243 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001244}
1245
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246void SurfaceFlinger::enableHardwareVsync() {
1247 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001248 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001249 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001250 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001252 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001253}
1254
Jesse Hall948fe0c2013-10-14 12:56:09 -07001255void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256 Mutex::Autolock _l(mHWVsyncLock);
1257
Jesse Hall948fe0c2013-10-14 12:56:09 -07001258 if (makeAvailable) {
1259 mHWVsyncAvailable = true;
1260 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001261 // Hardware vsync is not currently available, so abort the resync
1262 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001263 return;
1264 }
1265
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001266 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1267 if (!getHwComposer().isConnected(displayId)) {
1268 return;
1269 }
1270
1271 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001272 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273
1274 mPrimaryDispSync.reset();
1275 mPrimaryDispSync.setPeriod(period);
1276
1277 if (!mPrimaryHWVsyncEnabled) {
1278 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001279 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001280 mPrimaryHWVsyncEnabled = true;
1281 }
1282}
1283
Jesse Hall948fe0c2013-10-14 12:56:09 -07001284void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001285 Mutex::Autolock _l(mHWVsyncLock);
1286 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001287 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288 mPrimaryDispSync.endResync();
1289 mPrimaryHWVsyncEnabled = false;
1290 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001291 if (makeUnavailable) {
1292 mHWVsyncAvailable = false;
1293 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294}
1295
Tim Murray4a4e4a22016-04-19 16:29:23 +00001296void SurfaceFlinger::resyncWithRateLimit() {
1297 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001298
1299 // No explicit locking is needed here since EventThread holds a lock while calling this method
1300 static nsecs_t sLastResyncAttempted = 0;
1301 const nsecs_t now = systemTime();
1302 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001303 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001304 }
Dan Stoza57164302017-05-08 14:03:54 -07001305 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001306}
1307
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001308void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1309 int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001310 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001311 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001312 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001313 return;
1314 }
1315
1316 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001317 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001318 return;
1319 }
1320
Jamie Gennisd1700752013-10-14 12:22:52 -07001321 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001322
Jamie Gennisd1700752013-10-14 12:22:52 -07001323 { // Scope for the lock
1324 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001325 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001326 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001327 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001328 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001329
1330 if (needsHwVsync) {
1331 enableHardwareVsync();
1332 } else {
1333 disableHardwareVsync(false);
1334 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001335}
1336
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001337void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001338 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1339 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001340}
1341
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001342void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001343 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001344 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001345 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001346
Lloyd Piqueba04e622017-12-14 17:11:26 -08001347 // Ignore events that do not have the right sequenceId.
1348 if (sequenceId != getBE().mComposerSequenceId) {
1349 return;
1350 }
1351
Steven Thomasb02664d2017-07-26 18:48:28 -07001352 // Only lock if we're not on the main thread. This function is normally
1353 // called on a hwbinder thread, but for the primary display it's called on
1354 // the main thread with the state lock already held, so don't attempt to
1355 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001356 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001357
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001358 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001359
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001360 if (std::this_thread::get_id() == mMainThreadId) {
1361 // Process all pending hot plug events immediately if we are on the main thread.
1362 processDisplayHotplugEventsLocked();
1363 }
1364
Lloyd Piqueba04e622017-12-14 17:11:26 -08001365 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001366}
1367
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001368void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001369 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001370 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001372 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001373 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001374}
1375
Dan Stoza9e56aa02015-11-02 13:00:03 -08001376void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001377 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001379 getHwComposer().setVsyncEnabled(disp,
1380 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001381}
1382
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001383// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001384void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001385 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001386 // Clear the drawing state so that the logic inside of
1387 // handleTransactionLocked will fire. It will determine the delta between
1388 // mCurrentState and mDrawingState and re-apply all changes when we make the
1389 // transition.
1390 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001391 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001392 mDisplays.clear();
1393}
1394
Steven Thomas050b2c82017-03-06 11:45:16 -08001395void SurfaceFlinger::updateVrFlinger() {
1396 if (!mVrFlinger)
1397 return;
1398 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001399 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001400 return;
1401 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402
David Sodman105b7dc2017-11-04 20:28:14 -07001403 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001404 ALOGE("Vr flinger is only supported for remote hardware composer"
1405 " service connections. Ignoring request to transition to vr"
1406 " flinger.");
1407 mVrFlingerRequestsDisplay = false;
1408 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001409 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001410
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001411 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001412
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001413 const auto display = getDefaultDisplayDeviceLocked();
1414 LOG_ALWAYS_FATAL_IF(!display);
1415 const int currentDisplayPowerMode = display->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416
Steven Thomasb02664d2017-07-26 18:48:28 -07001417 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001418 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001420
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001422 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001423 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1424 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001425 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001426
David Sodman105b7dc2017-11-04 20:28:14 -07001427 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1428 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001429
1430 if (vrFlingerRequestsDisplay) {
1431 mVrFlinger->GrantDisplayOwnership();
1432 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001433 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001434 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001435
1436 mVisibleRegionsDirty = true;
1437 invalidateHwcGeometry();
1438
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001439 // Re-enable default display.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001440 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001441
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001443 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 const nsecs_t period = activeConfig->getVsyncPeriod();
1445 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001446
Steven Thomasb02664d2017-07-26 18:48:28 -07001447 // Use phase of 0 since phase is not known.
1448 // Use latency of 0, which will snap to the ideal latency.
1449 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001450
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001451 android_atomic_or(1, &mRepaintEverything);
1452 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001453}
1454
Mathias Agopian4fec8732012-06-29 14:12:52 -07001455void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001456 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001457 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001458 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001459 bool frameMissed = !mHadClientComposition &&
1460 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001461 (mPreviousPresentFence->getSignalTime() ==
1462 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001463 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001464 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001465 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001466 mTimeStats.incrementMissedFrames();
1467 if (mPropagateBackpressure) {
1468 signalLayerUpdate();
1469 break;
1470 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001471 }
Dan Stoza50182882016-07-08 12:02:20 -07001472
Steven Thomas050b2c82017-03-06 11:45:16 -08001473 // Now that we're going to make it to the handleMessageTransaction()
1474 // call below it's safe to call updateVrFlinger(), which will
1475 // potentially trigger a display handoff.
1476 updateVrFlinger();
1477
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478 bool refreshNeeded = handleMessageTransaction();
1479 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001480 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001481 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001482 // Signal a refresh if a transaction modified the window state,
1483 // a new buffer was latched, or if HWC has requested a full
1484 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001485 signalRefresh();
1486 }
1487 break;
1488 }
1489 case MessageQueue::REFRESH: {
1490 handleMessageRefresh();
1491 break;
1492 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001493 }
1494}
1495
Dan Stoza6b9454d2014-11-07 16:00:59 -08001496bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001497 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001498 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001499 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001500 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001501 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001502 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001503}
1504
Dan Stoza6b9454d2014-11-07 16:00:59 -08001505bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001506 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001507 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001508}
1509
1510void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001511 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001512
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001513 mRefreshPending = false;
1514
Chia-I Wu30505fb2018-03-26 16:20:31 -07001515 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001516
Chia-I Wu30505fb2018-03-26 16:20:31 -07001517 preComposition(refreshStartTime);
1518 rebuildLayerStacks();
1519 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001520 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001521 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001522 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001523 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001524 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001525
Dan Stozabfbffeb2016-07-21 14:49:33 -07001526 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001527 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001528 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001529 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001530 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001531 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001532
Dan Stoza9e56aa02015-11-02 13:00:03 -08001533 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001534}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001535
Mathias Agopiancd60f992012-08-16 16:28:27 -07001536void SurfaceFlinger::doDebugFlashRegions()
1537{
1538 // is debugging enabled
1539 if (CC_LIKELY(!mDebugRegion))
1540 return;
1541
1542 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001543 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001544 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001546 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547 if (!dirtyRegion.isEmpty()) {
1548 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001549 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001550
1551 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001552 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001553 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001554 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1555
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001556 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001557 }
1558 }
1559 }
1560
1561 postFramebuffer();
1562
1563 if (mDebugRegion > 1) {
1564 usleep(mDebugRegion * 1000);
1565 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001566
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001567 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001568 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001569 continue;
1570 }
1571
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001572 status_t result = display->prepareFrame(*getBE().mHwc);
1573 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001574 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001575 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001576}
1577
Adrian Roos1e1a1282017-11-01 19:05:31 +01001578void SurfaceFlinger::doTracing(const char* where) {
1579 ATRACE_CALL();
1580 ATRACE_NAME(where);
1581 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001582 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001583 }
1584}
1585
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001586void SurfaceFlinger::logLayerStats() {
1587 ATRACE_CALL();
1588 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001589 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001590 if (display->isPrimary()) {
1591 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001592 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001593 }
1594 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001595
1596 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001597 }
1598}
1599
Chia-I Wu30505fb2018-03-26 16:20:31 -07001600void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001601{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001602 ATRACE_CALL();
1603 ALOGV("preComposition");
1604
Mathias Agopiancd60f992012-08-16 16:28:27 -07001605 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001606 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001607 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001608 needExtraInvalidate = true;
1609 }
Robert Carr2047fae2016-11-28 14:09:09 -08001610 });
1611
Mathias Agopiancd60f992012-08-16 16:28:27 -07001612 if (needExtraInvalidate) {
1613 signalLayerUpdate();
1614 }
1615}
1616
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001617void SurfaceFlinger::updateCompositorTiming(
1618 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1619 std::shared_ptr<FenceTime>& presentFenceTime) {
1620 // Update queue of past composite+present times and determine the
1621 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001622 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001623 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001624 while (!getBE().mCompositePresentTimes.empty()) {
1625 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001626 // Cached values should have been updated before calling this method,
1627 // which helps avoid duplicate syscalls.
1628 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1629 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1630 break;
1631 }
1632 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001633 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001634 }
1635
1636 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001637 while (getBE().mCompositePresentTimes.size() > 16) {
1638 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001639 }
1640
Brian Andersond0010582017-03-07 13:20:31 -08001641 setCompositorTimingSnapped(
1642 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1643}
1644
1645void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1646 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001647 // Integer division and modulo round toward 0 not -inf, so we need to
1648 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001649 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1651 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1652
Brian Andersond0010582017-03-07 13:20:31 -08001653 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1654 if (idealLatency <= 0) {
1655 idealLatency = vsyncInterval;
1656 }
1657
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001658 // Snap the latency to a value that removes scheduling jitter from the
1659 // composition and present times, which often have >1ms of jitter.
1660 // Reducing jitter is important if an app attempts to extrapolate
1661 // something (such as user input) to an accurate diasplay time.
1662 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1663 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001664 nsecs_t bias = vsyncInterval / 2;
1665 int64_t extraVsyncs =
1666 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1667 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1668 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001669
David Sodman99974d22017-11-28 12:04:33 -08001670 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1671 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1672 getBE().mCompositorTiming.interval = vsyncInterval;
1673 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001674}
1675
Chia-I Wu30505fb2018-03-26 16:20:31 -07001676void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001677{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001678 ATRACE_CALL();
1679 ALOGV("postComposition");
1680
Brian Anderson3546a3f2016-07-14 11:51:14 -07001681 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001682 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001683 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001684 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001685 }
1686
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001687 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001688 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001689
David Sodman73beded2017-11-15 11:56:06 -08001690 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001691 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001692 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001693 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001694 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001695 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001696 } else {
1697 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1698 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001699
David Sodman73beded2017-11-15 11:56:06 -08001700 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001701 mPreviousPresentFence =
1702 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1703 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001704 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001705
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001706 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1707 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1708
Chia-I Wu30505fb2018-03-26 16:20:31 -07001709 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001710 // when we started doing work for this frame, but that should be okay
1711 // since updateCompositorTiming has snapping logic.
1712 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001713 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001714 CompositorTiming compositorTiming;
1715 {
David Sodman99974d22017-11-28 12:04:33 -08001716 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1717 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001718 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001719
Robert Carr2047fae2016-11-28 14:09:09 -08001720 mDrawingState.traverseInZOrder([&](Layer* layer) {
1721 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001722 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001723 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001724 recordBufferingStats(layer->getName().string(),
1725 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001726 }
Robert Carr2047fae2016-11-28 14:09:09 -08001727 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001728
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001729 if (presentFenceTime->isValid()) {
1730 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001731 enableHardwareVsync();
1732 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001733 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001734 }
1735 }
1736
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001737 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001738 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001739 enableHardwareVsync();
1740 }
1741 }
1742
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001743 if (mAnimCompositionPending) {
1744 mAnimCompositionPending = false;
1745
Brian Anderson4e606e32017-03-16 15:34:57 -07001746 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001747 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001748 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001749 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001750 // The HWC doesn't support present fences, so use the refresh
1751 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001752 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001753 mAnimFrameTracker.setActualPresentTime(presentTime);
1754 }
1755 mAnimFrameTracker.advanceFrame();
1756 }
Dan Stozab90cf072015-03-05 11:05:59 -08001757
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001758 mTimeStats.incrementTotalFrames();
1759 if (mHadClientComposition) {
1760 mTimeStats.incrementClientCompositionFrames();
1761 }
1762
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001763 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001764 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001765 return;
1766 }
1767
1768 nsecs_t currentTime = systemTime();
1769 if (mHasPoweredOff) {
1770 mHasPoweredOff = false;
1771 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001772 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001773 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001774 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1775 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001776 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001777 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001778 }
David Sodman4a36e932017-11-07 14:29:47 -08001779 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001780 }
David Sodman4a36e932017-11-07 14:29:47 -08001781 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001782
1783 {
1784 std::lock_guard lock(mTexturePoolMutex);
1785 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1786 if (refillCount > 0) {
1787 const size_t offset = mTexturePool.size();
1788 mTexturePool.resize(mTexturePoolSize);
1789 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1790 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1791 }
1792 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001793}
1794
1795void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001796 ATRACE_CALL();
1797 ALOGV("rebuildLayerStacks");
1798
Mathias Agopiancd60f992012-08-16 16:28:27 -07001799 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001800 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001801 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001802 mVisibleRegionsDirty = false;
1803 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001804
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001805 for (const auto& pair : mDisplays) {
1806 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001807 Region opaqueRegion;
1808 Region dirtyRegion;
1809 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001810 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001811 const Transform& tr = display->getTransform();
1812 const Rect bounds = display->getBounds();
1813 if (display->isPoweredOn()) {
1814 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001815
Jeff Sharkey76488112017-02-27 14:15:18 -07001816 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001817 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001818 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001819 Region drawRegion(tr.transform(
1820 layer->visibleNonTransparentRegion));
1821 drawRegion.andSelf(bounds);
1822 if (!drawRegion.isEmpty()) {
1823 layersSortedByZ.add(layer);
1824 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001825 // Clear out the HWC layer if this layer was
1826 // previously visible, but no longer is
Dominik Laskowski7e045462018-05-30 13:02:02 -07001827 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001828 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001829 } else {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001830 // WM changes display->layerStack upon sleep/awake.
Chia-I Wu30505fb2018-03-26 16:20:31 -07001831 // Here we make sure we delete the HWC layers even if
1832 // WM changed their layer stack.
Dominik Laskowski7e045462018-05-30 13:02:02 -07001833 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001834 }
1835
1836 // If a layer is not going to get a release fence because
1837 // it is invisible, but it is also going to release its
1838 // old buffer, add it to the list of layers needing
1839 // fences.
1840 if (hwcLayerDestroyed) {
1841 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1842 mLayersWithQueuedFrames.cend(), layer);
1843 if (found != mLayersWithQueuedFrames.cend()) {
1844 layersNeedingFences.add(layer);
1845 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001846 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001847 });
1848 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001849 display->setVisibleLayersSortedByZ(layersSortedByZ);
1850 display->setLayersNeedingFences(layersNeedingFences);
1851 display->undefinedRegion.set(bounds);
1852 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1853 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001854 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001855 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001856}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001857
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001858// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001859// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001860// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001861// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001862// The returned HDR data space is one of
1863// - Dataspace::UNKNOWN
1864// - Dataspace::BT2020_HLG
1865// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001866Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1867 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001868 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001869 *outHdrDataSpace = Dataspace::UNKNOWN;
1870
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001871 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001872 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001873 case Dataspace::V0_SCRGB:
1874 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001875 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001876 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001877 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001878 case Dataspace::BT2020_PQ:
1879 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001880 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001881 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001882 case Dataspace::BT2020_HLG:
1883 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001884 // When there's mixed PQ content and HLG content, we set the HDR
1885 // data space to be BT2020_PQ and convert HLG to PQ.
1886 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1887 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001888 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001889 break;
1890 default:
1891 break;
1892 }
Romain Guy54f154a2017-10-24 21:40:32 +01001893 }
1894
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001895 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001896}
1897
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001898// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001899void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1900 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001901 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1902 *outMode = ColorMode::NATIVE;
1903 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001904 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001905 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001906 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001907
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001908 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001909 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001910
Peiyong Lindfde5112018-06-05 10:58:41 -07001911 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001912 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001913 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001914 if (isHdr) {
1915 bestDataSpace = hdrDataSpace;
1916 }
1917
Chia-I Wu0d711262018-05-21 15:19:35 -07001918 RenderIntent intent;
1919 switch (mDisplayColorSetting) {
1920 case DisplayColorSetting::MANAGED:
1921 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001922 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001923 break;
1924 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001925 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001926 break;
1927 default: // vendor display color setting
1928 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1929 break;
1930 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001931
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001932 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001933}
1934
Chia-I Wu30505fb2018-03-26 16:20:31 -07001935void SurfaceFlinger::setUpHWComposer() {
1936 ATRACE_CALL();
1937 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001939 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001940 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
1941 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1942 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07001943
1944 // If nothing has changed (!dirty), don't recompose.
1945 // If something changed, but we don't currently have any visible layers,
1946 // and didn't when we last did a composition, then skip it this time.
1947 // The second rule does two things:
1948 // - When all layers are removed from a display, we'll emit one black
1949 // frame, then nothing more until we get new layers.
1950 // - When a display is created with a private layer stack, we won't
1951 // emit any black frames until a layer is added to the layer stack.
1952 bool mustRecompose = dirty && !(empty && wasEmpty);
1953
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001954 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001955 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
1956 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07001957
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001958 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001959
1960 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001961 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07001962 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001963 }
1964
Chia-I Wu30505fb2018-03-26 16:20:31 -07001965 // build the h/w work list
1966 if (CC_UNLIKELY(mGeometryInvalid)) {
1967 mGeometryInvalid = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001968 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001969 const auto displayId = display->getId();
1970 if (displayId >= 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001971 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001972 for (size_t i = 0; i < currentLayers.size(); i++) {
1973 const auto& layer = currentLayers[i];
Dominik Laskowski7e045462018-05-30 13:02:02 -07001974 if (!layer->hasHwcLayer(displayId)) {
1975 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1976 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001977 continue;
1978 }
1979 }
1980
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001981 layer->setGeometry(display, i);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001982 if (mDebugDisableHWC || mDebugRegion) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001983 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001984 }
1985 }
1986 }
1987 }
1988 }
1989
Chia-I Wu30505fb2018-03-26 16:20:31 -07001990 // Set the per-frame data
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001991 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001992 const auto displayId = display->getId();
1993 if (displayId < 0) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001994 continue;
1995 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07001996
Chia-I Wu28f320b2018-05-03 11:02:56 -07001997 if (mDrawingState.colorMatrixChanged) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001998 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski7e045462018-05-30 13:02:02 -07001999 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002000 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002001 displayId, result);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002002 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002003 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu692e0832018-06-05 15:46:58 -07002004 if (layer->isHdrY410()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002005 layer->forceClientComposition(displayId);
Chia-I Wu692e0832018-06-05 15:46:58 -07002006 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2007 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
2008 !display->hasHDR10Support()) {
2009 layer->forceClientComposition(displayId);
2010 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2011 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2012 !display->hasHLGSupport()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002013 layer->forceClientComposition(displayId);
Peiyong Linf59a7192018-04-25 11:19:31 -07002014 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002015
Dominik Laskowski7e045462018-05-30 13:02:02 -07002016 if (layer->getForceClientComposition(displayId)) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002017 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002018 layer->setCompositionType(displayId, HWC2::Composition::Client);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002019 continue;
2020 }
2021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002022 layer->setPerFrameData(display);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002023 }
2024
2025 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002026 ColorMode colorMode;
2027 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002028 RenderIntent renderIntent;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002029 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
2030 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002031 }
2032 }
2033
Chia-I Wu28f320b2018-05-03 11:02:56 -07002034 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07002035
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002036 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002037 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002038 continue;
2039 }
2040
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002041 status_t result = display->prepareFrame(*getBE().mHwc);
2042 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002043 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002044 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002045}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002046
Mathias Agopiancd60f992012-08-16 16:28:27 -07002047void SurfaceFlinger::doComposition() {
2048 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002049 ALOGV("doComposition");
2050
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002051 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002052 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002053 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002054 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002055 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002056
2057 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002058 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002059
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002060 display->dirtyRegion.clear();
2061 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002062 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002063 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002064 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002065}
2066
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002067void SurfaceFlinger::postFramebuffer()
2068{
Mathias Agopian841cde52012-03-01 15:44:37 -08002069 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002070 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002071
Mathias Agopiana44b0412011-10-16 18:46:35 -07002072 const nsecs_t now = systemTime();
2073 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002074
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002075 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002076 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002077 continue;
2078 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002079 const auto displayId = display->getId();
2080 if (displayId >= 0) {
2081 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002082 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002083 display->onSwapBuffersCompleted();
2084 display->makeCurrent();
2085 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002086 // The layer buffer from the previous frame (if any) is released
2087 // by HWC only when the release fence from this frame (if any) is
2088 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002089 auto hwcLayer = layer->getHwcLayer(displayId);
2090 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002091
2092 // If the layer was client composited in the previous frame, we
2093 // need to merge with the previous client target acquire fence.
2094 // Since we do not track that, always merge with the current
2095 // client target acquire fence when it is available, even though
2096 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002097 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002098 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002099 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002100 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002101
David Sodmanb8af7922017-12-21 15:17:55 -08002102 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002103 }
Chia-I Wu83806892017-11-16 10:50:20 -08002104
2105 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002106 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002107 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002108 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002109 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002110 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002111 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002112 }
2113 }
2114
Dominik Laskowski7e045462018-05-30 13:02:02 -07002115 if (displayId >= 0) {
2116 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002117 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002118 }
2119
Mathias Agopiana44b0412011-10-16 18:46:35 -07002120 mLastSwapBufferTime = systemTime() - now;
2121 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002122
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002123 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002124 const auto display = getDefaultDisplayDeviceLocked();
2125 if (display && getHwComposer().isConnected(display->getId())) {
2126 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002127 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2128 logFrameStats();
2129 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002130 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131}
2132
Mathias Agopian87baae12012-07-31 12:38:26 -07002133void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002134{
Mathias Agopian841cde52012-03-01 15:44:37 -08002135 ATRACE_CALL();
2136
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002137 // here we keep a copy of the drawing state (that is the state that's
2138 // going to be overwritten by handleTransactionLocked()) outside of
2139 // mStateLock so that the side-effects of the State assignment
2140 // don't happen with mStateLock held (which can cause deadlocks).
2141 State drawingState(mDrawingState);
2142
Mathias Agopianca4d3602011-05-19 15:38:14 -07002143 Mutex::Autolock _l(mStateLock);
2144 const nsecs_t now = systemTime();
2145 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002146
Mathias Agopianca4d3602011-05-19 15:38:14 -07002147 // Here we're guaranteed that some transaction flags are set
2148 // so we can call handleTransactionLocked() unconditionally.
2149 // We call getTransactionFlags(), which will also clear the flags,
2150 // with mStateLock held to guarantee that mCurrentState won't change
2151 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002152
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002153 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002154 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002155 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002156
Mathias Agopianca4d3602011-05-19 15:38:14 -07002157 mLastTransactionTime = systemTime() - now;
2158 mDebugInTransaction = 0;
2159 invalidateHwcGeometry();
2160 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002161}
2162
Dominik Laskowski7e045462018-05-30 13:02:02 -07002163DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002164 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002165 // Figure out whether the event is for the primary display or an
2166 // external display by matching the Hwc display id against one for a
2167 // connected display. If we did not find a match, we then check what
2168 // displays are not already connected to determine the type. If we don't
2169 // have a connected primary display, we assume the new display is meant to
2170 // be the primary display, and then if we don't have an external display,
2171 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002172 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2173 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002174 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002175 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002176 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002177 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002178 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002179 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002180 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002181 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002182 return DisplayDevice::DISPLAY_EXTERNAL;
2183 }
2184
2185 return DisplayDevice::DISPLAY_ID_INVALID;
2186}
2187
Lloyd Piqueba04e622017-12-14 17:11:26 -08002188void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2189 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002190 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002191 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002192 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002193 continue;
2194 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002195
2196 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2197 ALOGE("External displays are not supported by the vr hardware composer.");
2198 continue;
2199 }
2200
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002201 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002202 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002203 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002204 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002205 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002206
2207 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002208 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002209 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002210 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002211 DisplayDeviceState info;
2212 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002213 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2214 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002215 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002216 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002217 mInterceptor->saveDisplayCreation(info);
2218 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002219 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002220 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002221
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002222 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002223 if (idx >= 0) {
2224 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002225 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002226 mCurrentState.displays.removeItemsAt(idx);
2227 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002228 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002229 }
2230
2231 processDisplayChangesLocked();
2232 }
2233
2234 mPendingHotplugEvents.clear();
2235}
2236
Lloyd Pique99d3da52018-01-22 17:48:03 -08002237sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002238 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002239 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002240 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002241 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002242
Lloyd Pique99d3da52018-01-22 17:48:03 -08002243 if (hasWideColorDisplay) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002244 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002245 for (ColorMode colorMode : modes) {
2246 switch (colorMode) {
2247 case ColorMode::DISPLAY_P3:
2248 case ColorMode::ADOBE_RGB:
2249 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002250 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002251 break;
2252 default:
2253 break;
2254 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002255
Dominik Laskowski7e045462018-05-30 13:02:02 -07002256 std::vector<RenderIntent> renderIntents =
2257 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002258 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002259 }
2260 }
2261
Peiyong Lin62665892018-04-16 11:07:44 -07002262 HdrCapabilities hdrCapabilities;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002263 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002264
2265 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2266 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2267
2268 /*
2269 * Create our display's surface
2270 */
2271 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2272 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002273 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002274 renderSurface->setNativeWindow(nativeWindow.get());
2275 const int displayWidth = renderSurface->queryWidth();
2276 const int displayHeight = renderSurface->queryHeight();
2277
2278 // Make sure that composition can never be stalled by a virtual display
2279 // consumer that isn't processing buffers fast enough. We have to do this
2280 // in two places:
2281 // * Here, in case the display is composed entirely by HWC.
2282 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2283 // window's swap interval in eglMakeCurrent, so they'll override the
2284 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002285 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002286 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2287 }
2288
2289 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002290 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002291
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002292 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002293 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2294 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2295 displayHeight, hasWideColorGamut, hdrCapabilities,
2296 getHwComposer().getSupportedPerFrameMetadata(displayId),
2297 hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002298
2299 if (maxFrameBufferAcquiredBuffers >= 3) {
2300 nativeWindowSurface->preallocateBuffers();
2301 }
2302
2303 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002304 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2305 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002306 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002307 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002308 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002309 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002310 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002311 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002312 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002313 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002314 display->setLayerStack(state.layerStack);
2315 display->setProjection(state.orientation, state.viewport, state.frame);
2316 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002317
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002318 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002319}
2320
Lloyd Pique347200f2017-12-14 17:00:15 -08002321void SurfaceFlinger::processDisplayChangesLocked() {
2322 // here we take advantage of Vector's copy-on-write semantics to
2323 // improve performance by skipping the transaction entirely when
2324 // know that the lists are identical
2325 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2326 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2327 if (!curr.isIdenticalTo(draw)) {
2328 mVisibleRegionsDirty = true;
2329 const size_t cc = curr.size();
2330 size_t dc = draw.size();
2331
2332 // find the displays that were removed
2333 // (ie: in drawing state but not in current state)
2334 // also handle displays that changed
2335 // (ie: displays that are in both lists)
2336 for (size_t i = 0; i < dc;) {
2337 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2338 if (j < 0) {
2339 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002340 // Call makeCurrent() on the primary display so we can
2341 // be sure that nothing associated with this display
2342 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002343 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2344 defaultDisplay->makeCurrent();
2345 }
2346 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2347 display->disconnect(getHwComposer());
2348 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002349 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2350 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2351 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2352 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2353 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002354 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002355 } else {
2356 // this display is in both lists. see if something changed.
2357 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002358 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002359 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2360 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2361 if (state_binder != draw_binder) {
2362 // changing the surface is like destroying and
2363 // recreating the DisplayDevice, so we just remove it
2364 // from the drawing state, so that it get re-added
2365 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002366 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2367 display->disconnect(getHwComposer());
2368 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002369 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002370 mDrawingState.displays.removeItemsAt(i);
2371 dc--;
2372 // at this point we must loop to the next item
2373 continue;
2374 }
2375
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002376 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002377 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002378 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002379 }
2380 if ((state.orientation != draw[i].orientation) ||
2381 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002382 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002383 }
2384 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002385 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002386 }
2387 }
2388 }
2389 ++i;
2390 }
2391
2392 // find displays that were added
2393 // (ie: in current state but not in drawing state)
2394 for (size_t i = 0; i < cc; i++) {
2395 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2396 const DisplayDeviceState& state(curr[i]);
2397
2398 sp<DisplaySurface> dispSurface;
2399 sp<IGraphicBufferProducer> producer;
2400 sp<IGraphicBufferProducer> bqProducer;
2401 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002402 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002403
Dominik Laskowski7e045462018-05-30 13:02:02 -07002404 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002405 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002406 // Virtual displays without a surface are dormant:
2407 // they have external state (layer stack, projection,
2408 // etc.) but no internal state (i.e. a DisplayDevice).
2409 if (state.surface != nullptr) {
2410 // Allow VR composer to use virtual displays.
2411 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2412 int width = 0;
2413 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2414 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2415 int height = 0;
2416 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2417 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2418 int intFormat = 0;
2419 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2420 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002421 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002422
Dominik Laskowski7e045462018-05-30 13:02:02 -07002423 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2424 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002425 }
2426
2427 // TODO: Plumb requested format back up to consumer
2428
2429 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002430 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002431 bqProducer, bqConsumer,
2432 state.displayName);
2433
2434 dispSurface = vds;
2435 producer = vds;
2436 }
2437 } else {
2438 ALOGE_IF(state.surface != nullptr,
2439 "adding a supported display, but rendering "
2440 "surface is provided (%p), ignoring it",
2441 state.surface.get());
2442
Dominik Laskowski7e045462018-05-30 13:02:02 -07002443 displayId = state.type;
2444 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002445 producer = bqProducer;
2446 }
2447
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002448 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002449 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002450 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002451 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002452 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002453 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002454 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2455 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2456 true);
2457 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2458 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2459 true);
2460 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002461 }
2462 }
2463 }
2464 }
2465 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002466
2467 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002468}
2469
Mathias Agopian87baae12012-07-31 12:38:26 -07002470void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002471{
Dan Stoza7dde5992015-05-22 09:51:44 -07002472 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002473 mCurrentState.traverseInZOrder([](Layer* layer) {
2474 layer->notifyAvailableFrames();
2475 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002476
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002477 /*
2478 * Traversal of the children
2479 * (perform the transaction for each of them if needed)
2480 */
2481
Mathias Agopian3559b072012-08-15 13:46:03 -07002482 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002483 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002485 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486
2487 const uint32_t flags = layer->doTransaction(0);
2488 if (flags & Layer::eVisibleRegion)
2489 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002490 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491 }
2492
2493 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002494 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495 */
2496
Mathias Agopiane57f2922012-08-09 16:29:12 -07002497 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002498 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002499 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002500 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002502 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002503 // The transform hint might have changed for some layers
2504 // (either because a display has changed, or because a layer
2505 // as changed).
2506 //
2507 // Walk through all the layers in currentLayers,
2508 // and update their transform hint.
2509 //
2510 // If a layer is visible only on a single display, then that
2511 // display is used to calculate the hint, otherwise we use the
2512 // default display.
2513 //
2514 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2515 // the hint is set before we acquire a buffer from the surface texture.
2516 //
2517 // NOTE: layer transactions have taken place already, so we use their
2518 // drawing state. However, SurfaceFlinger's own transaction has not
2519 // happened yet, so we must use the current state layer list
2520 // (soon to become the drawing state list).
2521 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002522 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002523 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002524 bool first = true;
2525 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002526 // NOTE: we rely on the fact that layers are sorted by
2527 // layerStack first (so we don't have to traverse the list
2528 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002529 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002530 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002531 currentlayerStack = layerStack;
2532 // figure out if this layerstack is mirrored
2533 // (more than one display) if so, pick the default display,
2534 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002535 hintDisplay = nullptr;
2536 for (const auto& [token, display] : mDisplays) {
2537 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2538 if (hintDisplay) {
2539 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002540 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002541 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002542 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002543 }
2544 }
2545 }
2546 }
Chet Haase91d25932013-04-11 15:24:55 -07002547
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002548 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002549 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2550 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002551
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002552 // could be null when this layer is using a layerStack
2553 // that is not visible on any display. Also can occur at
2554 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002555 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002556 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002557
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002558 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002559 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002560 if (hintDisplay) {
2561 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002562 }
Robert Carr2047fae2016-11-28 14:09:09 -08002563
2564 first = false;
2565 });
Mathias Agopian84300952012-11-21 16:02:13 -08002566 }
2567
2568
Mathias Agopian3559b072012-08-15 13:46:03 -07002569 /*
2570 * Perform our own transaction if needed
2571 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002572
2573 if (mLayersAdded) {
2574 mLayersAdded = false;
2575 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002576 mVisibleRegionsDirty = true;
2577 }
2578
2579 // some layers might have been removed, so
2580 // we need to update the regions they're exposing.
2581 if (mLayersRemoved) {
2582 mLayersRemoved = false;
2583 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002584 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002585 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002586 // this layer is not visible anymore
2587 // TODO: we could traverse the tree from front to back and
2588 // compute the actual visible region
2589 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002590 Region visibleReg;
2591 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002592 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002593 }
Robert Carr2047fae2016-11-28 14:09:09 -08002594 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595 }
2596
2597 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002598
2599 updateCursorAsync();
2600}
2601
2602void SurfaceFlinger::updateCursorAsync()
2603{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002604 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002605 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002606 continue;
2607 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002608
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002609 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2610 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002611 }
2612 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002613}
2614
2615void SurfaceFlinger::commitTransaction()
2616{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002617 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002618 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002619 for (const auto& l : mLayersPendingRemoval) {
2620 recordBufferingStats(l->getName().string(),
2621 l->getOccupancyHistory(true));
2622 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002623 }
2624 mLayersPendingRemoval.clear();
2625 }
2626
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002627 // If this transaction is part of a window animation then the next frame
2628 // we composite should be considered an animation as well.
2629 mAnimCompositionPending = mAnimTransactionPending;
2630
Mathias Agopian4fec8732012-06-29 14:12:52 -07002631 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002632 // clear the "changed" flags in current state
2633 mCurrentState.colorMatrixChanged = false;
2634
Robert Carr1f0a16a2016-10-24 16:27:39 -07002635 mDrawingState.traverseInZOrder([](Layer* layer) {
2636 layer->commitChildList();
2637 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002638 mTransactionPending = false;
2639 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002640 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002641}
2642
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002643void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2644 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002645 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002646 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002647
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648 Region aboveOpaqueLayers;
2649 Region aboveCoveredLayers;
2650 Region dirty;
2651
Mathias Agopian87baae12012-07-31 12:38:26 -07002652 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653
Robert Carr2047fae2016-11-28 14:09:09 -08002654 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002655 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002656 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657
Jesse Hall01e29052013-02-19 16:13:35 -08002658 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002659 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002660 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002661 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002662
Mathias Agopianab028732010-03-16 16:41:46 -07002663 /*
2664 * opaqueRegion: area of a surface that is fully opaque.
2665 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002667
2668 /*
2669 * visibleRegion: area of a surface that is visible on screen
2670 * and not fully transparent. This is essentially the layer's
2671 * footprint minus the opaque regions above it.
2672 * Areas covered by a translucent surface are considered visible.
2673 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002674 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002675
2676 /*
2677 * coveredRegion: area of a surface that is covered by all
2678 * visible regions above it (which includes the translucent areas).
2679 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002681
Jesse Halla8026d22012-09-25 13:25:04 -07002682 /*
2683 * transparentRegion: area of a surface that is hinted to be completely
2684 * transparent. This is only used to tell when the layer has no visible
2685 * non-transparent regions and can be removed from the layer list. It
2686 * does not affect the visibleRegion of this layer or any layers
2687 * beneath it. The hint may not be correct if apps don't respect the
2688 * SurfaceView restrictions (which, sadly, some don't).
2689 */
2690 Region transparentRegion;
2691
Mathias Agopianab028732010-03-16 16:41:46 -07002692
2693 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002694 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002695 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002696 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002697 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002698 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002699 if (!visibleRegion.isEmpty()) {
2700 // Remove the transparent area from the visible region
2701 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002702 if (tr.preserveRects()) {
2703 // transform the transparent region
2704 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002705 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002706 // transformation too complex, can't do the
2707 // transparent region optimization.
2708 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002709 }
Mathias Agopianab028732010-03-16 16:41:46 -07002710 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002711
Mathias Agopianab028732010-03-16 16:41:46 -07002712 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002713 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002714 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002715 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2716 // the opaque region is the layer's footprint
2717 opaqueRegion = visibleRegion;
2718 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719 }
2720 }
2721
Robert Carre5f4f692018-01-12 13:12:28 -08002722 if (visibleRegion.isEmpty()) {
2723 layer->clearVisibilityRegions();
2724 return;
2725 }
2726
Mathias Agopianab028732010-03-16 16:41:46 -07002727 // Clip the covered region to the visible region
2728 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2729
2730 // Update aboveCoveredLayers for next (lower) layer
2731 aboveCoveredLayers.orSelf(visibleRegion);
2732
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733 // subtract the opaque region covered by the layers above us
2734 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735
2736 // compute this layer's dirty region
2737 if (layer->contentDirty) {
2738 // we need to invalidate the whole region
2739 dirty = visibleRegion;
2740 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002741 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742 layer->contentDirty = false;
2743 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002744 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002745 * the exposed region consists of two components:
2746 * 1) what's VISIBLE now and was COVERED before
2747 * 2) what's EXPOSED now less what was EXPOSED before
2748 *
2749 * note that (1) is conservative, we start with the whole
2750 * visible region but only keep what used to be covered by
2751 * something -- which mean it may have been exposed.
2752 *
2753 * (2) handles areas that were not covered by anything but got
2754 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002755 */
Mathias Agopianab028732010-03-16 16:41:46 -07002756 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002757 const Region oldVisibleRegion = layer->visibleRegion;
2758 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002759 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2760 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761 }
2762 dirty.subtractSelf(aboveOpaqueLayers);
2763
2764 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002765 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766
Mathias Agopianab028732010-03-16 16:41:46 -07002767 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002769
Jesse Halla8026d22012-09-25 13:25:04 -07002770 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771 layer->setVisibleRegion(visibleRegion);
2772 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002773 layer->setVisibleNonTransparentRegion(
2774 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002775 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776
Mathias Agopian87baae12012-07-31 12:38:26 -07002777 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778}
2779
Chia-I Wuab0c3192017-08-01 11:29:00 -07002780void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002781 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002782 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2783 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002784 }
2785 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002786}
2787
Dan Stoza6b9454d2014-11-07 16:00:59 -08002788bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002789{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002790 ALOGV("handlePageFlip");
2791
Brian Andersond6927fb2016-07-23 23:37:30 -07002792 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793
Mathias Agopian4fec8732012-06-29 14:12:52 -07002794 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002795 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002796 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002797
2798 // Store the set of layers that need updates. This set must not change as
2799 // buffers are being latched, as this could result in a deadlock.
2800 // Example: Two producers share the same command stream and:
2801 // 1.) Layer 0 is latched
2802 // 2.) Layer 0 gets a new frame
2803 // 2.) Layer 1 gets a new frame
2804 // 3.) Layer 1 is latched.
2805 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2806 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002807 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002808 if (layer->hasQueuedFrame()) {
2809 frameQueued = true;
2810 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002811 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002812 } else {
2813 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002814 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002815 } else {
2816 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002817 }
Robert Carr2047fae2016-11-28 14:09:09 -08002818 });
2819
Dan Stoza9e56aa02015-11-02 13:00:03 -08002820 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002821 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002822 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002823 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002824 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002825 newDataLatched = true;
2826 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002827 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002828
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002829 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002830
2831 // If we will need to wake up at some time in the future to deal with a
2832 // queued frame that shouldn't be displayed during this vsync period, wake
2833 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002834 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002835 signalLayerUpdate();
2836 }
2837
2838 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002839 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840}
2841
Mathias Agopianad456f92011-01-13 17:53:01 -08002842void SurfaceFlinger::invalidateHwcGeometry()
2843{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002844 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002845}
2846
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002847void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2848 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002849 // We only need to actually compose the display if:
2850 // 1) It is being handled by hardware composer, which may need this to
2851 // keep its virtual display state machine in sync, or
2852 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002853 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002854 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002855 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002856 return;
2857 }
2858
Dan Stoza9e56aa02015-11-02 13:00:03 -08002859 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002860 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002861
2862 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002863 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864}
2865
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002866bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002867 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002868
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002869 const Region bounds(display->bounds());
2870 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002871 const auto displayId = display->getId();
2872 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002873 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002874
Chia-I Wu8e50e692018-05-04 10:12:37 -07002875 bool applyColorMatrix = false;
Peiyong Lin00f9c022018-05-09 15:35:33 -07002876 bool needsLegacyColorMatrix = false;
2877 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002878
Dan Stoza9e56aa02015-11-02 13:00:03 -08002879 if (hasClientComposition) {
2880 ALOGV("hasClientComposition");
2881
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002882 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002883 if (display->hasWideColorGamut()) {
2884 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002885 }
2886 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002887 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002888 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002889
Dominik Laskowski7e045462018-05-30 13:02:02 -07002890 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002891 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2892 HWC2::Capability::SkipClientColorTransform);
2893
2894 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2895 if (applyColorMatrix) {
Peiyong Lin00f9c022018-05-09 15:35:33 -07002896 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002897 }
2898
Chia-I Wubbb44462018-05-21 15:33:27 -07002899 needsLegacyColorMatrix =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002900 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2901 outputDataspace != Dataspace::UNKNOWN && outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002902
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002903 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002904 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002905 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002906 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002907
2908 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002909 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2910 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2911 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002912 }
2913 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002914 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002915
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002916 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002917 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002918 // when using overlays, we assume a fully transparent framebuffer
2919 // NOTE: we could reduce how much we need to clear, for instance
2920 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002921 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002922 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002923 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002924 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002925 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002926 // we're left with the letterbox region
2927 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002928 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002929
2930 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002931 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002932
Mathias Agopianb9494d52012-04-18 02:28:45 -07002933 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002934 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002935 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002936 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002937 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002938 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002939
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002940 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002941 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002942 // scissor on the main display. It should never be needed
2943 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002944 const Rect& bounds = display->getBounds();
2945 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002946 if (scissor != bounds) {
2947 // scissor doesn't match the screen's dimensions, so we
2948 // need to clear everything outside of it and enable
2949 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002950
Mathias Agopianf45c5102012-10-24 16:29:17 -07002951 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002952 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002953 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002954 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002955 }
2956 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002957 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002958
Mathias Agopian85d751c2012-08-29 16:59:24 -07002959 /*
2960 * and then, render the layers targeted at the framebuffer
2961 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002962
Dan Stoza9e56aa02015-11-02 13:00:03 -08002963 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002964 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002965 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002966 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002967 const Region clip(bounds.intersect(
2968 displayTransform.transform(layer->visibleRegion)));
2969 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002970 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002971 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002972 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002973 case HWC2::Composition::Cursor:
2974 case HWC2::Composition::Device:
2975 case HWC2::Composition::Sideband:
2976 case HWC2::Composition::SolidColor: {
2977 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002978 if (layer->getClearClientTarget(displayId) && !firstLayer &&
2979 layer->isOpaque(state) && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002980 // never clear the very first layer since we're
2981 // guaranteed the FB is already cleared
2982 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002983 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002984 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002985 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002986 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002987 // switch color matrices lazily
Peiyong Lin00f9c022018-05-09 15:35:33 -07002988 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
2989 if (!legacyColorMatrixApplied) {
2990 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
2991 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002992 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07002993 } else if (legacyColorMatrixApplied) {
2994 getRenderEngine().setSaturationMatrix(mat4());
2995 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002996 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07002997
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002998 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002999 break;
3000 }
3001 default:
3002 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003003 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003004 } else {
3005 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003006 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003007 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003008 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003009
Peiyong Lin00f9c022018-05-09 15:35:33 -07003010 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003011 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003012 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07003013 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3014 getRenderEngine().setSaturationMatrix(mat4());
3015 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003016
Mathias Agopianf45c5102012-10-24 16:29:17 -07003017 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003018 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003019 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003020}
3021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003022void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3023 const Region& region) const {
3024 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003025 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003026 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003027}
3028
Dan Stoza7d89d062015-04-30 13:29:25 -07003029status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003030 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003031 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003032 const sp<Layer>& lbc,
3033 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003034{
Dan Stoza7d89d062015-04-30 13:29:25 -07003035 // add this layer to the current state list
3036 {
3037 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003038 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003039 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3040 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003041 return NO_MEMORY;
3042 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003043 if (parent == nullptr) {
3044 mCurrentState.layersSortedByZ.add(lbc);
3045 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003046 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003047 ALOGE("addClientLayer called with a removed parent");
3048 return NAME_NOT_FOUND;
3049 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003050 parent->addChild(lbc);
3051 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003052
Yiwei Zhang243b3782018-05-15 17:40:04 -07003053 if (gbc != nullptr) {
3054 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3055 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3056 mMaxGraphicBufferProducerListSize,
3057 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3058 mGraphicBufferProducerList.size(),
3059 mMaxGraphicBufferProducerListSize, mNumLayers);
3060 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003061 mLayersAdded = true;
3062 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003063 }
3064
Mathias Agopian96f08192010-06-02 23:28:45 -07003065 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003066 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003067
Dan Stoza7d89d062015-04-30 13:29:25 -07003068 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003069}
3070
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003071status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003072 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003073 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3074}
Robert Carr7f9b8992017-03-10 11:08:39 -08003075
chaviwca27f252018-02-06 16:46:39 -08003076status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3077 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003078 if (layer->isPendingRemoval()) {
3079 return NO_ERROR;
3080 }
3081
Robert Carr1f0a16a2016-10-24 16:27:39 -07003082 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003083 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003084 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003085 if (topLevelOnly) {
3086 return NO_ERROR;
3087 }
3088
Chia-I Wu98f1c102017-05-30 14:54:08 -07003089 sp<Layer> ancestor = p;
3090 while (ancestor->getParent() != nullptr) {
3091 ancestor = ancestor->getParent();
3092 }
3093 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3094 ALOGE("removeLayer called with a layer whose parent has been removed");
3095 return NAME_NOT_FOUND;
3096 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003097
3098 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003099 } else {
3100 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003101 }
3102
Robert Carr136e2f62017-02-08 17:54:29 -08003103 // As a matter of normal operation, the LayerCleaner will produce a second
3104 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3105 // so we will succeed in promoting it, but it's already been removed
3106 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3107 // otherwise something has gone wrong and we are leaking the layer.
3108 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003109 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3110 layer->getName().string(),
3111 (p != nullptr) ? p->getName().string() : "no-parent");
3112 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003113 } else if (index < 0) {
3114 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003115 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003116
Chia-I Wuc6657022017-08-15 11:18:17 -07003117 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003118 mLayersPendingRemoval.add(layer);
3119 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003120 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003121 setTransactionFlags(eTransactionNeeded);
3122 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003123}
3124
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003125uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003126 return android_atomic_release_load(&mTransactionFlags);
3127}
3128
Mathias Agopian3f844832013-08-07 21:24:32 -07003129uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003130 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3131}
3132
Mathias Agopian3f844832013-08-07 21:24:32 -07003133uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003134 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3135}
3136
3137uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3138 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003140 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003141 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003142 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143 }
3144 return old;
3145}
3146
chaviwca27f252018-02-06 16:46:39 -08003147bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3148 for (const ComposerState& state : states) {
3149 // Here we need to check that the interface we're given is indeed
3150 // one of our own. A malicious client could give us a nullptr
3151 // IInterface, or one of its own or even one of our own but a
3152 // different type. All these situations would cause us to crash.
3153 if (state.client == nullptr) {
3154 return true;
3155 }
3156
3157 sp<IBinder> binder = IInterface::asBinder(state.client);
3158 if (binder == nullptr) {
3159 return true;
3160 }
3161
3162 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3163 return true;
3164 }
3165 }
3166 return false;
3167}
3168
Mathias Agopian8b33f032012-07-24 20:43:54 -07003169void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003170 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003171 const Vector<DisplayState>& displays,
3172 uint32_t flags)
3173{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003174 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003175 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003176 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003177
chaviwca27f252018-02-06 16:46:39 -08003178 if (containsAnyInvalidClientState(states)) {
3179 return;
3180 }
3181
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003182 if (flags & eAnimation) {
3183 // For window updates that are part of an animation we must wait for
3184 // previous animation "frames" to be handled.
3185 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003186 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003187 if (CC_UNLIKELY(err != NO_ERROR)) {
3188 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003189 // caller after a few seconds.
3190 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3191 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003192 mAnimTransactionPending = false;
3193 break;
3194 }
3195 }
3196 }
3197
chaviwca27f252018-02-06 16:46:39 -08003198 for (const DisplayState& display : displays) {
3199 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003200 }
3201
chaviwca27f252018-02-06 16:46:39 -08003202 for (const ComposerState& state : states) {
3203 transactionFlags |= setClientStateLocked(state);
3204 }
3205
3206 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3207 // as destroyed should only occur after setting all other states. This is to allow for a
3208 // child re-parent to happen before marking its original parent as destroyed (which would
3209 // then mark the child as destroyed).
3210 for (const ComposerState& state : states) {
3211 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003212 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003213
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003214 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3215 // anyway. This can be used as a flush mechanism for previous async transactions.
3216 // Empty animation transaction can be used to simulate back-pressure, so also force a
3217 // transaction for empty animation transactions.
3218 if (transactionFlags == 0 &&
3219 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003220 transactionFlags = eTransactionNeeded;
3221 }
3222
Mathias Agopian386aa982011-11-07 21:58:03 -08003223 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003224 if (mInterceptor->isEnabled()) {
3225 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003226 }
Irvel468051e2016-06-13 16:44:44 -07003227
Mathias Agopian386aa982011-11-07 21:58:03 -08003228 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003229 const auto start = (flags & eEarlyWakeup)
3230 ? VSyncModulator::TransactionStart::EARLY
3231 : VSyncModulator::TransactionStart::NORMAL;
3232 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003233
3234 // if this is a synchronous transaction, wait for it to take effect
3235 // before returning.
3236 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003237 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003238 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003239 if (flags & eAnimation) {
3240 mAnimTransactionPending = true;
3241 }
3242 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003243 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3244 if (CC_UNLIKELY(err != NO_ERROR)) {
3245 // just in case something goes wrong in SF, return to the
3246 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003247 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3248 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003249 break;
3250 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003251 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252 }
3253}
3254
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003255uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3256 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3257 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003258
Mathias Agopiane57f2922012-08-09 16:29:12 -07003259 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003260 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3261
3262 const uint32_t what = s.what;
3263 if (what & DisplayState::eSurfaceChanged) {
3264 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3265 state.surface = s.surface;
3266 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003267 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003268 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003269 if (what & DisplayState::eLayerStackChanged) {
3270 if (state.layerStack != s.layerStack) {
3271 state.layerStack = s.layerStack;
3272 flags |= eDisplayTransactionNeeded;
3273 }
3274 }
3275 if (what & DisplayState::eDisplayProjectionChanged) {
3276 if (state.orientation != s.orientation) {
3277 state.orientation = s.orientation;
3278 flags |= eDisplayTransactionNeeded;
3279 }
3280 if (state.frame != s.frame) {
3281 state.frame = s.frame;
3282 flags |= eDisplayTransactionNeeded;
3283 }
3284 if (state.viewport != s.viewport) {
3285 state.viewport = s.viewport;
3286 flags |= eDisplayTransactionNeeded;
3287 }
3288 }
3289 if (what & DisplayState::eDisplaySizeChanged) {
3290 if (state.width != s.width) {
3291 state.width = s.width;
3292 flags |= eDisplayTransactionNeeded;
3293 }
3294 if (state.height != s.height) {
3295 state.height = s.height;
3296 flags |= eDisplayTransactionNeeded;
3297 }
3298 }
3299
Mathias Agopiane57f2922012-08-09 16:29:12 -07003300 return flags;
3301}
3302
Robert Carrd4ae7f32018-06-07 16:10:57 -07003303bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3304 IPCThreadState* ipc = IPCThreadState::self();
3305 const int pid = ipc->getCallingPid();
3306 const int uid = ipc->getCallingUid();
3307
3308 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3309 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3310 return false;
3311 }
3312 return true;
3313}
3314
chaviwca27f252018-02-06 16:46:39 -08003315uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3316 const layer_state_t& s = composerState.state;
3317 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3318
Mathias Agopian13127d82013-03-05 17:47:11 -08003319 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003320 if (layer == nullptr) {
3321 return 0;
3322 }
3323
3324 if (layer->isPendingRemoval()) {
3325 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3326 return 0;
3327 }
3328
3329 uint32_t flags = 0;
3330
3331 const uint32_t what = s.what;
3332 bool geometryAppliesWithResize =
3333 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003334
3335 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3336 // pending state will also be deferred.
3337 if (what & layer_state_t::eDeferTransaction) {
3338 layer->pushPendingState();
3339 }
3340
chaviw8b3871a2017-11-01 17:41:01 -07003341 if (what & layer_state_t::ePositionChanged) {
3342 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3343 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003344 }
chaviw8b3871a2017-11-01 17:41:01 -07003345 }
3346 if (what & layer_state_t::eLayerChanged) {
3347 // NOTE: index needs to be calculated before we update the state
3348 const auto& p = layer->getParent();
3349 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003350 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003351 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003352 mCurrentState.layersSortedByZ.removeAt(idx);
3353 mCurrentState.layersSortedByZ.add(layer);
3354 // we need traversal (state changed)
3355 // AND transaction (list changed)
3356 flags |= eTransactionNeeded|eTraversalNeeded;
3357 }
chaviw8b3871a2017-11-01 17:41:01 -07003358 } else {
3359 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003360 flags |= eTransactionNeeded|eTraversalNeeded;
3361 }
3362 }
chaviw8b3871a2017-11-01 17:41:01 -07003363 }
3364 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003365 // NOTE: index needs to be calculated before we update the state
3366 const auto& p = layer->getParent();
3367 if (p == nullptr) {
3368 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3369 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3370 mCurrentState.layersSortedByZ.removeAt(idx);
3371 mCurrentState.layersSortedByZ.add(layer);
3372 // we need traversal (state changed)
3373 // AND transaction (list changed)
3374 flags |= eTransactionNeeded|eTraversalNeeded;
3375 }
3376 } else {
3377 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3378 flags |= eTransactionNeeded|eTraversalNeeded;
3379 }
chaviw8b3871a2017-11-01 17:41:01 -07003380 }
3381 }
3382 if (what & layer_state_t::eSizeChanged) {
3383 if (layer->setSize(s.w, s.h)) {
3384 flags |= eTraversalNeeded;
3385 }
3386 }
3387 if (what & layer_state_t::eAlphaChanged) {
3388 if (layer->setAlpha(s.alpha))
3389 flags |= eTraversalNeeded;
3390 }
3391 if (what & layer_state_t::eColorChanged) {
3392 if (layer->setColor(s.color))
3393 flags |= eTraversalNeeded;
3394 }
3395 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003396 // TODO: b/109894387
3397 //
3398 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3399 // rotation. To see the problem observe that if we have a square parent, and a child
3400 // of the same size, then we rotate the child 45 degrees around it's center, the child
3401 // must now be cropped to a non rectangular 8 sided region.
3402 //
3403 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3404 // private API, and the WindowManager only uses rotation in one case, which is on a top
3405 // level layer in which cropping is not an issue.
3406 //
3407 // However given that abuse of rotation matrices could lead to surfaces extending outside
3408 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3409 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3410 // transformations.
3411 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003412 flags |= eTraversalNeeded;
3413 }
3414 if (what & layer_state_t::eTransparentRegionChanged) {
3415 if (layer->setTransparentRegionHint(s.transparentRegion))
3416 flags |= eTraversalNeeded;
3417 }
3418 if (what & layer_state_t::eFlagsChanged) {
3419 if (layer->setFlags(s.flags, s.mask))
3420 flags |= eTraversalNeeded;
3421 }
3422 if (what & layer_state_t::eCropChanged) {
3423 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3424 flags |= eTraversalNeeded;
3425 }
3426 if (what & layer_state_t::eFinalCropChanged) {
3427 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3428 flags |= eTraversalNeeded;
3429 }
3430 if (what & layer_state_t::eLayerStackChanged) {
3431 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3432 // We only allow setting layer stacks for top level layers,
3433 // everything else inherits layer stack from its parent.
3434 if (layer->hasParent()) {
3435 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3436 layer->getName().string());
3437 } else if (idx < 0) {
3438 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3439 "that also does not appear in the top level layer list. Something"
3440 " has gone wrong.", layer->getName().string());
3441 } else if (layer->setLayerStack(s.layerStack)) {
3442 mCurrentState.layersSortedByZ.removeAt(idx);
3443 mCurrentState.layersSortedByZ.add(layer);
3444 // we need traversal (state changed)
3445 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003446 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003447 }
3448 }
3449 if (what & layer_state_t::eDeferTransaction) {
3450 if (s.barrierHandle != nullptr) {
3451 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3452 } else if (s.barrierGbp != nullptr) {
3453 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3454 if (authenticateSurfaceTextureLocked(gbp)) {
3455 const auto& otherLayer =
3456 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3457 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3458 } else {
3459 ALOGE("Attempt to defer transaction to to an"
3460 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003461 }
3462 }
chaviw8b3871a2017-11-01 17:41:01 -07003463 // We don't trigger a traversal here because if no other state is
3464 // changed, we don't want this to cause any more work
3465 }
3466 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003467 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003468 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003469 if (!hadParent) {
3470 mCurrentState.layersSortedByZ.remove(layer);
3471 }
chaviw8b3871a2017-11-01 17:41:01 -07003472 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003473 }
chaviw8b3871a2017-11-01 17:41:01 -07003474 }
3475 if (what & layer_state_t::eReparentChildren) {
3476 if (layer->reparentChildren(s.reparentHandle)) {
3477 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003478 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003479 }
chaviw8b3871a2017-11-01 17:41:01 -07003480 if (what & layer_state_t::eDetachChildren) {
3481 layer->detachChildren();
3482 }
3483 if (what & layer_state_t::eOverrideScalingModeChanged) {
3484 layer->setOverrideScalingMode(s.overrideScalingMode);
3485 // We don't trigger a traversal here because if no other state is
3486 // changed, we don't want this to cause any more work
3487 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003488 return flags;
3489}
3490
chaviwca27f252018-02-06 16:46:39 -08003491void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3492 const layer_state_t& state = composerState.state;
3493 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3494
3495 sp<Layer> layer(client->getLayerUser(state.surface));
3496 if (layer == nullptr) {
3497 return;
3498 }
3499
3500 if (layer->isPendingRemoval()) {
3501 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3502 return;
3503 }
3504
3505 if (state.what & layer_state_t::eDestroySurface) {
3506 removeLayerLocked(mStateLock, layer);
3507 }
3508}
3509
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003510status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003511 const String8& name,
3512 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003513 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003514 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003515 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003516{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003517 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003518 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003519 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003520 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003521 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003522
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003523 status_t result = NO_ERROR;
3524
3525 sp<Layer> layer;
3526
Cody Northropbc755282017-03-31 12:00:08 -06003527 String8 uniqueName = getUniqueLayerName(name);
3528
Mathias Agopian3165cc22012-08-08 19:42:09 -07003529 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3530 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003531 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003532 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003533 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003534
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003535 break;
chaviw13fdc492017-06-27 12:40:18 -07003536 case ISurfaceComposerClient::eFXSurfaceColor:
3537 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003538 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003539 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003540 break;
3541 default:
3542 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003543 break;
3544 }
3545
Dan Stoza7d89d062015-04-30 13:29:25 -07003546 if (result != NO_ERROR) {
3547 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003548 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003549
Chia-I Wuab0c3192017-08-01 11:29:00 -07003550 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3551 // TODO b/64227542
3552 if (windowType == 441731) {
3553 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3554 layer->setPrimaryDisplayOnly();
3555 }
3556
Albert Chaulk479c60c2017-01-27 14:21:34 -05003557 layer->setInfo(windowType, ownerUid);
3558
Robert Carr1f0a16a2016-10-24 16:27:39 -07003559 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003560 if (result != NO_ERROR) {
3561 return result;
3562 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003563 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003564
3565 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003566 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003567}
3568
Cody Northropbc755282017-03-31 12:00:08 -06003569String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3570{
3571 bool matchFound = true;
3572 uint32_t dupeCounter = 0;
3573
3574 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3575 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3576
Dan Stoza436ccf32018-06-21 12:10:12 -07003577 // Grab the state lock since we're accessing mCurrentState
3578 Mutex::Autolock lock(mStateLock);
3579
Cody Northropbc755282017-03-31 12:00:08 -06003580 // Loop over layers until we're sure there is no matching name
3581 while (matchFound) {
3582 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003583 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003584 if (layer->getName() == uniqueName) {
3585 matchFound = true;
3586 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3587 }
3588 });
3589 }
3590
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003591 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3592 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003593
3594 return uniqueName;
3595}
3596
David Sodman0c69cad2017-08-21 12:12:51 -07003597status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003598 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3599 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003600{
3601 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003602 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003603 case PIXEL_FORMAT_TRANSPARENT:
3604 case PIXEL_FORMAT_TRANSLUCENT:
3605 format = PIXEL_FORMAT_RGBA_8888;
3606 break;
3607 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003608 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609 break;
3610 }
3611
David Sodman0c69cad2017-08-21 12:12:51 -07003612 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3613 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003614 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003615 *handle = layer->getHandle();
3616 *gbp = layer->getProducer();
3617 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003618 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003619
David Sodman0c69cad2017-08-21 12:12:51 -07003620 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003621 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003622}
3623
chaviw13fdc492017-06-27 12:40:18 -07003624status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003625 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003626 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003627{
chaviw13fdc492017-06-27 12:40:18 -07003628 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003629 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003630 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003631}
3632
Mathias Agopianac9fa422013-02-11 16:40:36 -08003633status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003634{
Robert Carr9524cb32017-02-13 11:32:32 -08003635 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003636 status_t err = NO_ERROR;
3637 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003638 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003639 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003640 err = removeLayer(l);
3641 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3642 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003643 }
3644 return err;
3645}
3646
Mathias Agopian13127d82013-03-05 17:47:11 -08003647status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003648{
Mathias Agopian67106042013-03-14 19:18:13 -07003649 // called by ~LayerCleaner() when all references to the IBinder (handle)
3650 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003651 sp<Layer> l = layer.promote();
3652 if (l == nullptr) {
3653 // The layer has already been removed, carry on
3654 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003655 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003656 // If we have a parent, then we can continue to live as long as it does.
3657 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003658}
3659
Mathias Agopianb60314a2012-04-10 22:09:54 -07003660// ---------------------------------------------------------------------------
3661
Andy McFadden13a082e2012-08-24 10:16:42 -07003662void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003663 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3664 if (!displayToken) return;
3665
Jesse Hall01e29052013-02-19 16:13:35 -08003666 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003667 Vector<ComposerState> state;
3668 Vector<DisplayState> displays;
3669 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003670 d.what = DisplayState::eDisplayProjectionChanged |
3671 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003672 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003673 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003674 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003675 d.frame.makeInvalid();
3676 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003677 d.width = 0;
3678 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003679 displays.add(d);
3680 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003681
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003682 const auto display = getDisplayDevice(displayToken);
3683 if (!display) return;
3684
3685 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3686
3687 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003688 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003689 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003690
Brian Andersond0010582017-03-07 13:20:31 -08003691 // Use phase of 0 since phase is not known.
3692 // Use latency of 0, which will snap to the ideal latency.
3693 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003694}
3695
3696void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003697 // Async since we may be called from the main thread.
3698 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003699}
3700
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003701void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3702 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003703 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003704 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003705
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003706 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003707 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003708 return;
3709 }
3710
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003711 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003712 ALOGW("Trying to set power mode for virtual display");
3713 return;
3714 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003715
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003716 display->setPowerMode(mode);
3717
Lloyd Pique4dccc412018-01-22 17:21:36 -08003718 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003719 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003720 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003721 if (idx < 0) {
3722 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3723 return;
3724 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003725 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003726 }
3727
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003728 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003729 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003730 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003731 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003732 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003733 // FIXME: eventthread only knows about the main display right now
3734 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003735 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003736 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003737
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003738 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003739 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003740 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003741
3742 struct sched_param param = {0};
3743 param.sched_priority = 1;
3744 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3745 ALOGW("Couldn't set SCHED_FIFO on display on");
3746 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003747 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003748 // Turn off the display
3749 struct sched_param param = {0};
3750 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3751 ALOGW("Couldn't set SCHED_OTHER on display off");
3752 }
3753
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003754 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003755 disableHardwareVsync(true); // also cancels any in-progress resync
3756
Mathias Agopiancde87a32012-09-13 14:09:01 -07003757 // FIXME: eventthread only knows about the main display right now
3758 mEventThread->onScreenReleased();
3759 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003760
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003761 getHwComposer().setPowerMode(type, mode);
3762 mVisibleRegionsDirty = true;
3763 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003764 } else if (mode == HWC_POWER_MODE_DOZE ||
3765 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003766 // Update display while dozing
3767 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003768 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003769 // FIXME: eventthread only knows about the main display right now
3770 mEventThread->onScreenAcquired();
3771 resyncToHardwareVsync(true);
3772 }
3773 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3774 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003775 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003776 disableHardwareVsync(true); // also cancels any in-progress resync
3777 // FIXME: eventthread only knows about the main display right now
3778 mEventThread->onScreenReleased();
3779 }
3780 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003781 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003782 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003783 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003784 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003785
3786 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003787}
3788
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003789void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003790 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003791 const auto display = getDisplayDevice(displayToken);
3792 if (!display) {
3793 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3794 displayToken.get());
3795 } else if (display->isVirtual()) {
3796 ALOGW("Attempt to set power mode %d for virtual display", mode);
3797 } else {
3798 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003799 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003800 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003801}
3802
3803// ---------------------------------------------------------------------------
3804
Lloyd Pique755e3192018-01-31 16:46:15 -08003805status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3806 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003807 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003808
Mathias Agopianbd115332013-04-18 16:41:04 -07003809 IPCThreadState* ipc = IPCThreadState::self();
3810 const int pid = ipc->getCallingPid();
3811 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003812
Mathias Agopianbd115332013-04-18 16:41:04 -07003813 if ((uid != AID_SHELL) &&
3814 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003815 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003816 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003817 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003818 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003819 // (this would indicate SF is stuck, but we want to be able to
3820 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003821 status_t err = mStateLock.timedLock(s2ns(1));
3822 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003823 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003824 result.appendFormat(
3825 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3826 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003827 }
3828
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003829 bool dumpAll = true;
3830 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003831 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003832
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003833 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003834 if ((index < numArgs) &&
3835 (args[index] == String16("--list"))) {
3836 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003837 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003838 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003839 }
3840
3841 if ((index < numArgs) &&
3842 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003843 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003844 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003845 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003846 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003847
3848 if ((index < numArgs) &&
3849 (args[index] == String16("--latency-clear"))) {
3850 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003851 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003852 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003853 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003854
3855 if ((index < numArgs) &&
3856 (args[index] == String16("--dispsync"))) {
3857 index++;
3858 mPrimaryDispSync.dump(result);
3859 dumpAll = false;
3860 }
Dan Stozab90cf072015-03-05 11:05:59 -08003861
3862 if ((index < numArgs) &&
3863 (args[index] == String16("--static-screen"))) {
3864 index++;
3865 dumpStaticScreenStats(result);
3866 dumpAll = false;
3867 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003868
3869 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003870 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003871 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003872 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003873 dumpAll = false;
3874 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003875
3876 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3877 index++;
3878 dumpWideColorInfo(result);
3879 dumpAll = false;
3880 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003881
3882 if ((index < numArgs) &&
3883 (args[index] == String16("--enable-layer-stats"))) {
3884 index++;
3885 mLayerStats.enable();
3886 dumpAll = false;
3887 }
3888
3889 if ((index < numArgs) &&
3890 (args[index] == String16("--disable-layer-stats"))) {
3891 index++;
3892 mLayerStats.disable();
3893 dumpAll = false;
3894 }
3895
3896 if ((index < numArgs) &&
3897 (args[index] == String16("--clear-layer-stats"))) {
3898 index++;
3899 mLayerStats.clear();
3900 dumpAll = false;
3901 }
3902
3903 if ((index < numArgs) &&
3904 (args[index] == String16("--dump-layer-stats"))) {
3905 index++;
3906 mLayerStats.dump(result);
3907 dumpAll = false;
3908 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003909
3910 if ((index < numArgs) &&
3911 (args[index] == String16("--display-identification"))) {
3912 index++;
3913 dumpDisplayIdentificationData(result);
3914 dumpAll = false;
3915 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003916
3917 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3918 index++;
3919 mTimeStats.parseArgs(asProto, args, index, result);
3920 dumpAll = false;
3921 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003922 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003923
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003924 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003925 if (asProto) {
3926 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3927 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3928 } else {
3929 dumpAllLocked(args, index, result);
3930 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003931 }
3932
Mathias Agopian9795c422009-08-26 16:36:26 -07003933 if (locked) {
3934 mStateLock.unlock();
3935 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003936 }
3937 write(fd, result.string(), result.size());
3938 return NO_ERROR;
3939}
3940
Dan Stozac7014012014-02-14 15:03:43 -08003941void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3942 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003943{
Robert Carr2047fae2016-11-28 14:09:09 -08003944 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003945 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003946 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003947}
3948
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003949void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003950 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003951{
3952 String8 name;
3953 if (index < args.size()) {
3954 name = String8(args[index]);
3955 index++;
3956 }
3957
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003958 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3959 getHwComposer().isConnected(displayId)) {
3960 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3961 const nsecs_t period = activeConfig->getVsyncPeriod();
3962 result.appendFormat("%" PRId64 "\n", period);
3963 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003964
3965 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003966 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003967 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003968 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003969 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003970 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003971 }
Robert Carr2047fae2016-11-28 14:09:09 -08003972 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003973 }
3974}
3975
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003976void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003977 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003978{
3979 String8 name;
3980 if (index < args.size()) {
3981 name = String8(args[index]);
3982 index++;
3983 }
3984
Robert Carr2047fae2016-11-28 14:09:09 -08003985 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003986 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003987 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003988 }
Robert Carr2047fae2016-11-28 14:09:09 -08003989 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003990
Svetoslavd85084b2014-03-20 10:28:31 -07003991 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003992}
3993
Jamie Gennis6547ff42013-07-16 20:12:42 -07003994// This should only be called from the main thread. Otherwise it would need
3995// the lock and should use mCurrentState rather than mDrawingState.
3996void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003997 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003998 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003999 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004000
4001 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4002}
4003
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004004void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004005{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004006 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004007
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004008 if (isLayerTripleBufferingDisabled())
4009 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004010
4011 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004012 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004013 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004014 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004015 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4016 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004017 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004018}
4019
Dan Stozab90cf072015-03-05 11:05:59 -08004020void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4021{
4022 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004023 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4024 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004025 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004026 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004027 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4028 b + 1, bucketTimeSec, percent);
4029 }
David Sodman4a36e932017-11-07 14:29:47 -08004030 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004031 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004032 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004033 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004034 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004035}
4036
Dan Stozae77c7662016-05-13 11:37:28 -07004037void SurfaceFlinger::recordBufferingStats(const char* layerName,
4038 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004039 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4040 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004041 for (const auto& segment : history) {
4042 if (!segment.usedThirdBuffer) {
4043 stats.twoBufferTime += segment.totalTime;
4044 }
4045 if (segment.occupancyAverage < 1.0f) {
4046 stats.doubleBufferedTime += segment.totalTime;
4047 } else if (segment.occupancyAverage < 2.0f) {
4048 stats.tripleBufferedTime += segment.totalTime;
4049 }
4050 ++stats.numSegments;
4051 stats.totalTime += segment.totalTime;
4052 }
4053}
4054
Brian Andersond6927fb2016-07-23 23:37:30 -07004055void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4056 result.appendFormat("Layer frame timestamps:\n");
4057
4058 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4059 const size_t count = currentLayers.size();
4060 for (size_t i=0 ; i<count ; i++) {
4061 currentLayers[i]->dumpFrameEvents(result);
4062 }
4063}
4064
Dan Stozae77c7662016-05-13 11:37:28 -07004065void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4066 result.append("Buffering stats:\n");
4067 result.append(" [Layer name] <Active time> <Two buffer> "
4068 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004069 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004070 typedef std::tuple<std::string, float, float, float> BufferTuple;
4071 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004072 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004073 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004074 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004075 if (stats.numSegments == 0) {
4076 continue;
4077 }
4078 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4079 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4080 stats.totalTime;
4081 float doubleBufferRatio = static_cast<float>(
4082 stats.doubleBufferedTime) / stats.totalTime;
4083 float tripleBufferRatio = static_cast<float>(
4084 stats.tripleBufferedTime) / stats.totalTime;
4085 sorted.insert({activeTime, {name, twoBufferRatio,
4086 doubleBufferRatio, tripleBufferRatio}});
4087 }
4088 for (const auto& sortedPair : sorted) {
4089 float activeTime = sortedPair.first;
4090 const BufferTuple& values = sortedPair.second;
4091 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4092 std::get<0>(values).c_str(), activeTime,
4093 std::get<1>(values), std::get<2>(values),
4094 std::get<3>(values));
4095 }
4096 result.append("\n");
4097}
4098
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004099void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004100 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004101 const int32_t displayId = display->getId();
4102 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4103 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004104 continue;
4105 }
4106
Dominik Laskowski7e045462018-05-30 13:02:02 -07004107 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004108 uint8_t port;
4109 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004110 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004111 result.append("no identification data\n");
4112 continue;
4113 }
4114
4115 if (!isEdid(data)) {
4116 result.append("unknown identification data: ");
4117 for (uint8_t byte : data) {
4118 result.appendFormat("%x ", byte);
4119 }
4120 result.append("\n");
4121 continue;
4122 }
4123
4124 const auto edid = parseEdid(data);
4125 if (!edid) {
4126 result.append("invalid EDID: ");
4127 for (uint8_t byte : data) {
4128 result.appendFormat("%x ", byte);
4129 }
4130 result.append("\n");
4131 continue;
4132 }
4133
4134 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4135 result.append(edid->displayName.data(), edid->displayName.length());
4136 result.append("\"\n");
4137 }
4138 result.append("\n");
4139}
4140
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004141void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4142 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004143 result.appendFormat("DisplayColorSetting: %s\n",
4144 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004145
4146 // TODO: print out if wide-color mode is active or not
4147
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004148 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004149 const int32_t displayId = display->getId();
4150 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004151 continue;
4152 }
4153
Dominik Laskowski7e045462018-05-30 13:02:02 -07004154 result.appendFormat("Display %d color modes:\n", displayId);
4155 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004156 for (auto&& mode : modes) {
4157 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4158 }
4159
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004160 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004161 result.appendFormat(" Current color mode: %s (%d)\n",
4162 decodeColorMode(currentMode).c_str(), currentMode);
4163 }
4164 result.append("\n");
4165}
4166
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004167LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004168 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004169 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4170 const State& state = useDrawing ? mDrawingState : mCurrentState;
4171 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004172 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004173 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004174 });
4175
4176 return layersProto;
4177}
4178
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004179LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004180 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004181
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004182 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004183 resolution->set_w(display.getWidth());
4184 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004185
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004186 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4187 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4188 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004189
Dominik Laskowski7e045462018-05-30 13:02:02 -07004190 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004191 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004192 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004193 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004194 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004195 }
4196 });
4197
4198 return layersProto;
4199}
4200
Mathias Agopian74d211a2013-04-22 16:55:35 +02004201void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4202 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004203{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004204 bool colorize = false;
4205 if (index < args.size()
4206 && (args[index] == String16("--color"))) {
4207 colorize = true;
4208 index++;
4209 }
4210
4211 Colorizer colorizer(colorize);
4212
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004213 // figure out if we're stuck somewhere
4214 const nsecs_t now = systemTime();
4215 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4216 const nsecs_t inTransaction(mDebugInTransaction);
4217 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4218 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4219
4220 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004221 * Dump library configuration.
4222 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004223
4224 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004225 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004226 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004227 appendSfConfigString(result);
4228 appendUiConfigString(result);
4229 appendGuiConfigString(result);
4230 result.append("\n");
4231
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004232 result.append("\nDisplay identification data:\n");
4233 dumpDisplayIdentificationData(result);
4234
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004235 result.append("\nWide-Color information:\n");
4236 dumpWideColorInfo(result);
4237
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004238 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004239 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004240 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004241 result.append(SyncFeatures::getInstance().toString());
4242 result.append("\n");
4243
Andy McFadden41d67d72014-04-25 16:58:34 -07004244 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004245 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004246 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004247
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004248 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4249 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004250 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4251 getHwComposer().isConnected(displayId)) {
4252 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004253 result.appendFormat("Display %d: "
4254 "app phase %" PRId64 " ns, "
4255 "sf phase %" PRId64 " ns, "
4256 "early app phase %" PRId64 " ns, "
4257 "early sf phase %" PRId64 " ns, "
4258 "early app gl phase %" PRId64 " ns, "
4259 "early sf gl phase %" PRId64 " ns, "
4260 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4261 displayId,
4262 vsyncPhaseOffsetNs,
4263 sfVsyncPhaseOffsetNs,
4264 appEarlyOffset,
4265 sfEarlyOffset,
4266 appEarlyGlOffset,
4267 sfEarlyOffset,
4268 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004269 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004270 result.append("\n");
4271
Dan Stozab90cf072015-03-05 11:05:59 -08004272 // Dump static screen stats
4273 result.append("\n");
4274 dumpStaticScreenStats(result);
4275 result.append("\n");
4276
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004277 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4278
Dan Stozae77c7662016-05-13 11:37:28 -07004279 dumpBufferingStats(result);
4280
Andy McFadden4803b742012-09-24 19:07:20 -07004281 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004282 * Dump the visible layer list
4283 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004284 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004285 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004286 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4287 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004288 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004289
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004290 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004291 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004292 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004293 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004294
4295 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004296 * Dump Display state
4297 */
4298
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004299 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004300 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004301 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004302 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004303 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004304 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004305 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004306
4307 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004308 * Dump SurfaceFlinger global state
4309 */
4310
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004311 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004312 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004313 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004314
Mathias Agopian888c8222012-08-04 21:10:38 -07004315 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004316 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004317
David Sodmanbc815282017-11-05 18:57:52 -08004318 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004319
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004320 if (display) {
4321 display->undefinedRegion.dump(result, "undefinedRegion");
4322 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4323 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004324 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004325 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4326 " last transaction time : %f us\n"
4327 " transaction-flags : %08x\n"
4328 " gpu_to_cpu_unsupported : %d\n",
4329 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4330 mTransactionFlags, !mGpuToCpuSupported);
4331
4332 if (display) {
4333 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4334 result.appendFormat(" refresh-rate : %f fps\n"
4335 " x-dpi : %f\n"
4336 " y-dpi : %f\n",
4337 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4338 activeConfig->getDpiY());
4339 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004340
Mathias Agopian74d211a2013-04-22 16:55:35 +02004341 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004342 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004343
Mathias Agopian74d211a2013-04-22 16:55:35 +02004344 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004345 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004346
4347 /*
4348 * VSYNC state
4349 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004350 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004351 result.append("\n");
4352
4353 /*
4354 * HWC layer minidump
4355 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004356 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004357 const int32_t displayId = display->getId();
4358 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004359 continue;
4360 }
4361
Dominik Laskowski7e045462018-05-30 13:02:02 -07004362 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004363 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004364 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004365 result.append("\n");
4366 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004367
4368 /*
4369 * Dump HWComposer state
4370 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004371 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004372 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004373 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004374 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004375 result.appendFormat(" h/w composer %s\n",
4376 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004377 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004378
4379 /*
4380 * Dump gralloc state
4381 */
4382 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4383 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004384
4385 /*
4386 * Dump VrFlinger state if in use.
4387 */
4388 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4389 result.append("VrFlinger state:\n");
4390 result.append(mVrFlinger->Dump().c_str());
4391 result.append("\n");
4392 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004393}
4394
Dominik Laskowski7e045462018-05-30 13:02:02 -07004395const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004396 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004397 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004398 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004399 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004400 }
4401 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004402
4403 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4404 static const Vector<sp<Layer>> empty;
4405 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004406}
4407
Keun young Park63f165f2012-08-31 10:53:36 -07004408bool SurfaceFlinger::startDdmConnection()
4409{
4410 void* libddmconnection_dso =
4411 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4412 if (!libddmconnection_dso) {
4413 return false;
4414 }
4415 void (*DdmConnection_start)(const char* name);
4416 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004417 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004418 if (!DdmConnection_start) {
4419 dlclose(libddmconnection_dso);
4420 return false;
4421 }
4422 (*DdmConnection_start)(getServiceName());
4423 return true;
4424}
4425
Chia-I Wu28f320b2018-05-03 11:02:56 -07004426void SurfaceFlinger::updateColorMatrixLocked() {
4427 mat4 colorMatrix;
4428 if (mGlobalSaturationFactor != 1.0f) {
4429 // Rec.709 luma coefficients
4430 float3 luminance{0.213f, 0.715f, 0.072f};
4431 luminance *= 1.0f - mGlobalSaturationFactor;
4432 mat4 saturationMatrix = mat4(
4433 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4434 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4435 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4436 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4437 );
4438 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4439 } else {
4440 colorMatrix = mClientColorMatrix * mDaltonizer();
4441 }
4442
4443 if (mCurrentState.colorMatrix != colorMatrix) {
4444 mCurrentState.colorMatrix = colorMatrix;
4445 mCurrentState.colorMatrixChanged = true;
4446 setTransactionFlags(eTransactionNeeded);
4447 }
4448}
4449
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004450status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004451 switch (code) {
4452 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004453 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004454 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004455 case CLEAR_ANIMATION_FRAME_STATS:
4456 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004457 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004458 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004459 case ENABLE_VSYNC_INJECTIONS:
4460 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004461 {
4462 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004463 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4464 IPCThreadState* ipc = IPCThreadState::self();
4465 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4466 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004467 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004468 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004469 break;
4470 }
Robert Carr1db73f62016-12-21 12:58:51 -08004471 /*
4472 * Calling setTransactionState is safe, because you need to have been
4473 * granted a reference to Client* and Handle* to do anything with it.
4474 *
4475 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4476 */
4477 case SET_TRANSACTION_STATE:
4478 case CREATE_SCOPED_CONNECTION:
4479 {
4480 return OK;
4481 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004482 case CAPTURE_SCREEN:
4483 {
4484 // codes that require permission check
4485 IPCThreadState* ipc = IPCThreadState::self();
4486 const int pid = ipc->getCallingPid();
4487 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004488 if ((uid != AID_GRAPHICS) &&
4489 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004490 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004491 return PERMISSION_DENIED;
4492 }
4493 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004494 }
chaviwa76b2712017-09-20 12:02:26 -07004495 case CAPTURE_LAYERS: {
4496 IPCThreadState* ipc = IPCThreadState::self();
4497 const int pid = ipc->getCallingPid();
4498 const int uid = ipc->getCallingUid();
4499 if ((uid != AID_GRAPHICS) &&
4500 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4501 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4502 return PERMISSION_DENIED;
4503 }
4504 break;
4505 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004506 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004507 return OK;
4508}
4509
4510status_t SurfaceFlinger::onTransact(
4511 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4512{
4513 status_t credentialCheck = CheckTransactCodeCredentials(code);
4514 if (credentialCheck != OK) {
4515 return credentialCheck;
4516 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004517
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004518 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4519 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004520 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004521 IPCThreadState* ipc = IPCThreadState::self();
4522 const int uid = ipc->getCallingUid();
4523 if (CC_UNLIKELY(uid != AID_SYSTEM
4524 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004525 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004526 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004527 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004528 return PERMISSION_DENIED;
4529 }
4530 int n;
4531 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004532 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004533 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004534 return NO_ERROR;
4535 case 1002: // SHOW_UPDATES
4536 n = data.readInt32();
4537 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004538 invalidateHwcGeometry();
4539 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004540 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004541 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004542 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004543 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004544 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004545 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004546 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004547 setTransactionFlags(
4548 eTransactionNeeded|
4549 eDisplayTransactionNeeded|
4550 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004551 return NO_ERROR;
4552 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004553 case 1006:{ // send empty update
4554 signalRefresh();
4555 return NO_ERROR;
4556 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004557 case 1008: // toggle use of hw composer
4558 n = data.readInt32();
4559 mDebugDisableHWC = n ? 1 : 0;
4560 invalidateHwcGeometry();
4561 repaintEverything();
4562 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004563 case 1009: // toggle use of transform hint
4564 n = data.readInt32();
4565 mDebugDisableTransformHint = n ? 1 : 0;
4566 invalidateHwcGeometry();
4567 repaintEverything();
4568 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004569 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004570 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004571 reply->writeInt32(0);
4572 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004573 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004574 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004575 return NO_ERROR;
4576 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004577 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004578 if (!display) {
4579 return NAME_NOT_FOUND;
4580 }
4581
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004582 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004583 return NO_ERROR;
4584 }
4585 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004586 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004587 // daltonize
4588 n = data.readInt32();
4589 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004590 case 1:
4591 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4592 break;
4593 case 2:
4594 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4595 break;
4596 case 3:
4597 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4598 break;
4599 default:
4600 mDaltonizer.setType(ColorBlindnessType::None);
4601 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004602 }
4603 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004604 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004605 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004606 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004607 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004608
4609 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004610 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004611 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004612 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004613 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004614 // apply a color matrix
4615 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004616 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004617 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004618 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004619 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004620 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004621 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004622 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004623 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004624 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004625 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004626
4627 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4628 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004629 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004630 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4631 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4632 }
4633
Chia-I Wu28f320b2018-05-03 11:02:56 -07004634 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004635 return NO_ERROR;
4636 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004637 // This is an experimental interface
4638 // Needs to be shifted to proper binder interface when we productize
4639 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004640 n = data.readInt32();
4641 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004642 return NO_ERROR;
4643 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004644 case 1017: {
4645 n = data.readInt32();
4646 mForceFullDamage = static_cast<bool>(n);
4647 return NO_ERROR;
4648 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004649 case 1018: { // Modify Choreographer's phase offset
4650 n = data.readInt32();
4651 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4652 return NO_ERROR;
4653 }
4654 case 1019: { // Modify SurfaceFlinger's phase offset
4655 n = data.readInt32();
4656 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4657 return NO_ERROR;
4658 }
Irvel468051e2016-06-13 16:44:44 -07004659 case 1020: { // Layer updates interceptor
4660 n = data.readInt32();
4661 if (n) {
4662 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004663 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004664 }
4665 else{
4666 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004667 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004668 }
4669 return NO_ERROR;
4670 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004671 case 1021: { // Disable HWC virtual displays
4672 n = data.readInt32();
4673 mUseHwcVirtualDisplays = !n;
4674 return NO_ERROR;
4675 }
Romain Guy0147a172017-06-01 13:53:56 -07004676 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004677 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004678 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004679
Chia-I Wu28f320b2018-05-03 11:02:56 -07004680 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004681 return NO_ERROR;
4682 }
Romain Guy54f154a2017-10-24 21:40:32 +01004683 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004684 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004685 invalidateHwcGeometry();
4686 repaintEverything();
4687 return NO_ERROR;
4688 }
4689 case 1024: { // Is wide color gamut rendering/color management supported?
4690 reply->writeBool(hasWideColorDisplay);
4691 return NO_ERROR;
4692 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004693 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004694 n = data.readInt32();
4695 if (n) {
4696 ALOGV("LayerTracing enabled");
4697 mTracing.enable();
4698 doTracing("tracing.enable");
4699 reply->writeInt32(NO_ERROR);
4700 } else {
4701 ALOGV("LayerTracing disabled");
4702 status_t err = mTracing.disable();
4703 reply->writeInt32(err);
4704 }
4705 return NO_ERROR;
4706 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004707 case 1026: { // Get layer tracing status
4708 reply->writeBool(mTracing.isEnabled());
4709 return NO_ERROR;
4710 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004711 // Is a DisplayColorSetting supported?
4712 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004713 const auto display = getDefaultDisplayDevice();
4714 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004715 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004716 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004717
4718 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4719 switch (setting) {
4720 case DisplayColorSetting::MANAGED:
4721 reply->writeBool(hasWideColorDisplay);
4722 break;
4723 case DisplayColorSetting::UNMANAGED:
4724 reply->writeBool(true);
4725 break;
4726 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004727 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004728 break;
4729 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004730 reply->writeBool(
4731 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004732 break;
4733 }
4734 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004735 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004736 // Is VrFlinger active?
4737 case 1028: {
4738 Mutex::Autolock _l(mStateLock);
4739 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4740 return NO_ERROR;
4741 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004742 }
4743 }
4744 return err;
4745}
4746
Steven Thomas6d8110b2017-08-31 18:24:21 -07004747void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004748 android_atomic_or(1, &mRepaintEverything);
4749 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004750}
4751
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004752// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4753class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004754public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004755 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4756 ~WindowDisconnector() {
4757 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004758 }
4759
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004760private:
4761 ANativeWindow* mWindow;
4762 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004763};
4764
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004765status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4766 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4767 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4768 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004769 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004770 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004771
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004772 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004773
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004774 const auto display = getDisplayDeviceLocked(displayToken);
4775 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004776
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004777 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004778
4779 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004780 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004781 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004782}
4783
4784status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004785 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004786 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004787 ATRACE_CALL();
4788
4789 class LayerRenderArea : public RenderArea {
4790 public:
Robert Carr578038f2018-03-09 12:25:24 -08004791 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4792 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004793 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004794 mLayer(layer),
4795 mCrop(crop),
4796 mFlinger(flinger),
4797 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004798 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004799 Rect getBounds() const override {
4800 const Layer::State& layerState(mLayer->getDrawingState());
4801 return Rect(layerState.active.w, layerState.active.h);
4802 }
4803 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4804 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4805 bool isSecure() const override { return false; }
4806 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004807 Rect getSourceCrop() const override {
4808 if (mCrop.isEmpty()) {
4809 return getBounds();
4810 } else {
4811 return mCrop;
4812 }
4813 }
Robert Carr578038f2018-03-09 12:25:24 -08004814 class ReparentForDrawing {
4815 public:
4816 const sp<Layer>& oldParent;
4817 const sp<Layer>& newParent;
4818
4819 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4820 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004821 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004822 }
Robert Carr15eae092018-03-23 13:43:53 -07004823 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004824 };
4825
4826 void render(std::function<void()> drawLayers) override {
4827 if (!mChildrenOnly) {
4828 mTransform = mLayer->getTransform().inverse();
4829 drawLayers();
4830 } else {
4831 Rect bounds = getBounds();
4832 screenshotParentLayer =
4833 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4834 bounds.getWidth(), bounds.getHeight(), 0);
4835
4836 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4837 drawLayers();
4838 }
4839 }
chaviwa76b2712017-09-20 12:02:26 -07004840
chaviwa76b2712017-09-20 12:02:26 -07004841 private:
chaviw7206d492017-11-10 16:16:12 -08004842 const sp<Layer> mLayer;
4843 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004844
4845 // In the "childrenOnly" case we reparent the children to a screenshot
4846 // layer which has no properties set and which does not draw.
4847 sp<ContainerLayer> screenshotParentLayer;
4848 Transform mTransform;
4849
4850 SurfaceFlinger* mFlinger;
4851 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004852 };
4853
4854 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4855 auto parent = layerHandle->owner.promote();
4856
chaviw7206d492017-11-10 16:16:12 -08004857 if (parent == nullptr || parent->isPendingRemoval()) {
4858 ALOGE("captureLayers called with a removed parent");
4859 return NAME_NOT_FOUND;
4860 }
4861
Robert Carr578038f2018-03-09 12:25:24 -08004862 const int uid = IPCThreadState::self()->getCallingUid();
4863 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4864 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4865 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4866 return PERMISSION_DENIED;
4867 }
4868
chaviw7206d492017-11-10 16:16:12 -08004869 Rect crop(sourceCrop);
4870 if (sourceCrop.width() <= 0) {
4871 crop.left = 0;
4872 crop.right = parent->getCurrentState().active.w;
4873 }
4874
4875 if (sourceCrop.height() <= 0) {
4876 crop.top = 0;
4877 crop.bottom = parent->getCurrentState().active.h;
4878 }
4879
4880 int32_t reqWidth = crop.width() * frameScale;
4881 int32_t reqHeight = crop.height() * frameScale;
4882
Robert Carr578038f2018-03-09 12:25:24 -08004883 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004884
Robert Carr578038f2018-03-09 12:25:24 -08004885 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004886 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4887 if (!layer->isVisible()) {
4888 return;
Robert Carr578038f2018-03-09 12:25:24 -08004889 } else if (childrenOnly && layer == parent.get()) {
4890 return;
chaviwa76b2712017-09-20 12:02:26 -07004891 }
4892 visitor(layer);
4893 });
4894 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004895 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004896}
4897
4898status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4899 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004900 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004901 bool useIdentityTransform) {
4902 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004903
Iris Chang7501ed62018-04-30 14:45:42 +08004904 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004905
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004906 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4907 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4908 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4909 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004910
4911 // This mutex protects syncFd and captureResult for communication of the return values from the
4912 // main thread back to this Binder thread
4913 std::mutex captureMutex;
4914 std::condition_variable captureCondition;
4915 std::unique_lock<std::mutex> captureLock(captureMutex);
4916 int syncFd = -1;
4917 std::optional<status_t> captureResult;
4918
Robert Carr03480e22018-01-04 16:02:06 -08004919 const int uid = IPCThreadState::self()->getCallingUid();
4920 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4921
Dominik Laskowski8c001672018-05-30 16:52:06 -07004922 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004923 // If there is a refresh pending, bug out early and tell the binder thread to try again
4924 // after the refresh.
4925 if (mRefreshPending) {
4926 ATRACE_NAME("Skipping screenshot for now");
4927 std::unique_lock<std::mutex> captureLock(captureMutex);
4928 captureResult = std::make_optional<status_t>(EAGAIN);
4929 captureCondition.notify_one();
4930 return;
4931 }
4932
4933 status_t result = NO_ERROR;
4934 int fd = -1;
4935 {
4936 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07004937 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08004938 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4939 useIdentityTransform, forSystem, &fd);
4940 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004941 }
4942
4943 {
4944 std::unique_lock<std::mutex> captureLock(captureMutex);
4945 syncFd = fd;
4946 captureResult = std::make_optional<status_t>(result);
4947 captureCondition.notify_one();
4948 }
4949 });
4950
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004951 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004952 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004953 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004954 while (*captureResult == EAGAIN) {
4955 captureResult.reset();
4956 result = postMessageAsync(message);
4957 if (result != NO_ERROR) {
4958 return result;
4959 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07004960 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004961 }
4962 result = *captureResult;
4963 }
4964
4965 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004966 sync_wait(syncFd, -1);
4967 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004968 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004969
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004970 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004971}
4972
chaviwa76b2712017-09-20 12:02:26 -07004973void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4974 TraverseLayersFunction traverseLayers, bool yswap,
4975 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004976 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004977
Lloyd Pique144e1162017-12-20 16:44:52 -08004978 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004979
4980 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004981 const auto raWidth = renderArea.getWidth();
4982 const auto raHeight = renderArea.getHeight();
4983
4984 const auto reqWidth = renderArea.getReqWidth();
4985 const auto reqHeight = renderArea.getReqHeight();
4986 Rect sourceCrop = renderArea.getSourceCrop();
4987
Iris Chang7501ed62018-04-30 14:45:42 +08004988 bool filtering = false;
4989 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4990 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
4991 static_cast<int32_t>(reqHeight) != raWidth;
4992 } else {
4993 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4994 static_cast<int32_t>(reqHeight) != raHeight;
4995 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004996
Dan Stozac1879002014-05-22 15:59:05 -07004997 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004998 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004999 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005000 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005001 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5002 Transform tr;
5003 uint32_t flags = 0x00;
5004 switch (mPrimaryDisplayOrientation) {
5005 case DisplayState::eOrientation90:
5006 flags = Transform::ROT_90;
5007 break;
5008 case DisplayState::eOrientation180:
5009 flags = Transform::ROT_180;
5010 break;
5011 case DisplayState::eOrientation270:
5012 flags = Transform::ROT_270;
5013 break;
5014 }
5015 tr.set(flags, raWidth, raHeight);
5016 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005017 }
5018
5019 // ensure that sourceCrop is inside screen
5020 if (sourceCrop.left < 0) {
5021 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5022 }
chaviwa76b2712017-09-20 12:02:26 -07005023 if (sourceCrop.right > raWidth) {
5024 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005025 }
5026 if (sourceCrop.top < 0) {
5027 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5028 }
chaviwa76b2712017-09-20 12:02:26 -07005029 if (sourceCrop.bottom > raHeight) {
5030 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005031 }
5032
Chia-I Wu36574d92018-05-16 10:54:36 -07005033 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5034 engine.setOutputDataSpace(Dataspace::SRGB);
5035 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005036
Mathias Agopian180f10d2013-04-10 22:55:41 -07005037 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005038 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005039
Iris Chang7501ed62018-04-30 14:45:42 +08005040 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5041 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5042 // convert hw orientation into flag presentation
5043 // here inverse transform needed
5044 uint8_t hw_rot_90 = 0x00;
5045 uint8_t hw_flip_hv = 0x00;
5046 switch (mPrimaryDisplayOrientation) {
5047 case DisplayState::eOrientation90:
5048 hw_rot_90 = Transform::ROT_90;
5049 hw_flip_hv = Transform::ROT_180;
5050 break;
5051 case DisplayState::eOrientation180:
5052 hw_flip_hv = Transform::ROT_180;
5053 break;
5054 case DisplayState::eOrientation270:
5055 hw_rot_90 = Transform::ROT_90;
5056 break;
5057 }
5058
5059 // transform flags operation
5060 // 1) flip H V if both have ROT_90 flag
5061 // 2) XOR these flags
5062 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5063 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5064 if (rotation_rot_90 & hw_rot_90) {
5065 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5066 }
5067 rotation = static_cast<Transform::orientation_flags>
5068 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5069 }
5070
Mathias Agopian180f10d2013-04-10 22:55:41 -07005071 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005072 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005073 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005074 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005075
chaviw50da5042018-04-09 13:49:37 -07005076 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005077 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005078 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005079
chaviwa76b2712017-09-20 12:02:26 -07005080 traverseLayers([&](Layer* layer) {
5081 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07005082 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005083 if (filtering) layer->setFiltering(false);
5084 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005085}
5086
chaviwa76b2712017-09-20 12:02:26 -07005087status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5088 TraverseLayersFunction traverseLayers,
5089 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005090 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005091 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005092 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005093 ATRACE_CALL();
5094
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005095 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005096
5097 traverseLayers([&](Layer* layer) {
5098 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5099 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005100
Robert Carr03480e22018-01-04 16:02:06 -08005101 // We allow the system server to take screenshots of secure layers for
5102 // use in situations like the Screen-rotation animation and place
5103 // the impetus on WindowManager to not persist them.
5104 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005105 ALOGW("FB is protected: PERMISSION_DENIED");
5106 return PERMISSION_DENIED;
5107 }
5108
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005109 // this binds the given EGLImage as a framebuffer for the
5110 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005111 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005112 if (bufferBond.getStatus() != NO_ERROR) {
5113 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005114 return INVALID_OPERATION;
5115 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005116
Dan Stozaabcda352017-06-01 14:37:39 -07005117 // this will in fact render into our dequeued buffer
5118 // via an FBO, which means we didn't have to create
5119 // an EGLSurface and therefore we're not
5120 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005121 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005122
Dan Stozaabcda352017-06-01 14:37:39 -07005123 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005124 getRenderEngine().finish();
5125 *outSyncFd = -1;
5126
chaviwa76b2712017-09-20 12:02:26 -07005127 const auto reqWidth = renderArea.getReqWidth();
5128 const auto reqHeight = renderArea.getReqHeight();
5129
Dan Stozaabcda352017-06-01 14:37:39 -07005130 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5131 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005132 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005133 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005134 } else {
5135 base::unique_fd syncFd = getRenderEngine().flush();
5136 if (syncFd < 0) {
5137 getRenderEngine().finish();
5138 }
5139 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005140 }
5141
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005142 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005143}
5144
Mathias Agopiand5556842013-09-19 17:08:37 -07005145void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005146 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005147 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005148 for (size_t y = 0; y < h; y++) {
5149 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5150 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005151 if (p[x] != 0xFF000000) return;
5152 }
5153 }
chaviwa76b2712017-09-20 12:02:26 -07005154 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005155
Robert Carr2047fae2016-11-28 14:09:09 -08005156 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005157 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005158 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005159 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5160 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5161 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5162 static_cast<float>(state.color.a));
5163 i++;
5164 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005165 }
5166}
5167
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005168// ---------------------------------------------------------------------------
5169
Dan Stoza412903f2017-04-27 13:42:17 -07005170void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5171 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005172}
5173
Dan Stoza412903f2017-04-27 13:42:17 -07005174void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5175 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005176}
5177
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005178void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5179 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005180 const LayerVector::Visitor& visitor) {
5181 // We loop through the first level of layers without traversing,
5182 // as we need to interpret min/max layer Z in the top level Z space.
5183 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005184 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005185 continue;
5186 }
5187 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005188 // relative layers are traversed in Layer::traverseInZOrder
5189 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005190 continue;
5191 }
5192 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005193 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005194 return;
5195 }
chaviwa76b2712017-09-20 12:02:26 -07005196 if (!layer->isVisible()) {
5197 return;
5198 }
5199 visitor(layer);
5200 });
5201 }
5202}
5203
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005204}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005205
Chia-I Wu30505fb2018-03-26 16:20:31 -07005206
Mathias Agopian3f844832013-08-07 21:24:32 -07005207#if defined(__gl_h_)
5208#error "don't include gl/gl.h in this file"
5209#endif
5210
5211#if defined(__gl2_h_)
5212#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005213#endif