blob: 488bc20f3d31401a2c653beaece3175163876300 [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),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800226 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800227 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700228 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700229 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700230 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700231 mDebugInSwapBuffers(0),
232 mLastSwapBufferTime(0),
233 mDebugInTransaction(0),
234 mLastTransactionTime(0),
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
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800501 postMessageAsync(new LambdaMessage([this] {
502 readPersistentProperties();
503 mBootStage = BootStage::FINISHED;
504 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800505}
506
Dan Stoza436ccf32018-06-21 12:10:12 -0700507uint32_t SurfaceFlinger::getNewTexture() {
508 {
509 std::lock_guard lock(mTexturePoolMutex);
510 if (!mTexturePool.empty()) {
511 uint32_t name = mTexturePool.back();
512 mTexturePool.pop_back();
513 ATRACE_INT("TexturePoolSize", mTexturePool.size());
514 return name;
515 }
516
517 // The pool was too small, so increase it for the future
518 ++mTexturePoolSize;
519 }
520
521 // The pool was empty, so we need to get a new texture name directly using a
522 // blocking call to the main thread
523 uint32_t name = 0;
524 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
525 return name;
526}
527
Mathias Agopian3f844832013-08-07 21:24:32 -0700528void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700529 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700530}
531
Lloyd Piquee83f9312018-02-01 12:53:17 -0800532class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700534 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000535 const char* name) :
536 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700537 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700538 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000539 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
540 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700541 mDispSync(dispSync),
542 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700543 mVsyncMutex(),
544 mPhaseOffset(phaseOffset),
545 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700546
Lloyd Piquee83f9312018-02-01 12:53:17 -0800547 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700548
Lloyd Piquee83f9312018-02-01 12:53:17 -0800549 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700550 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700551 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000552 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700553 static_cast<DispSync::Callback*>(this));
554 if (err != NO_ERROR) {
555 ALOGE("error registering vsync callback: %s (%d)",
556 strerror(-err), err);
557 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700558 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700559 } else {
560 status_t err = mDispSync->removeEventListener(
561 static_cast<DispSync::Callback*>(this));
562 if (err != NO_ERROR) {
563 ALOGE("error unregistering vsync callback: %s (%d)",
564 strerror(-err), err);
565 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700566 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700567 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700568 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700569 }
570
Lloyd Piquee83f9312018-02-01 12:53:17 -0800571 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700572 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700573 mCallback = callback;
574 }
575
Lloyd Piquee83f9312018-02-01 12:53:17 -0800576 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700577 Mutex::Autolock lock(mVsyncMutex);
578
579 // Normalize phaseOffset to [0, period)
580 auto period = mDispSync->getPeriod();
581 phaseOffset %= period;
582 if (phaseOffset < 0) {
583 // If we're here, then phaseOffset is in (-period, 0). After this
584 // operation, it will be in (0, period)
585 phaseOffset += period;
586 }
587 mPhaseOffset = phaseOffset;
588
589 // If we're not enabled, we don't need to mess with the listeners
590 if (!mEnabled) {
591 return;
592 }
593
Dan Stoza84d619e2018-03-28 17:07:36 -0700594 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
595 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700596 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700597 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700598 strerror(-err), err);
599 }
600 }
601
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602private:
603 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800604 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700605 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700606 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700607 callback = mCallback;
608
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700609 if (mTraceVsync) {
610 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700611 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700612 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700613 }
614
Peiyong Lin566a3b42018-01-09 18:22:43 -0800615 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700616 callback->onVSyncEvent(when);
617 }
618 }
619
Tim Murray4a4e4a22016-04-19 16:29:23 +0000620 const char* const mName;
621
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700622 int mValue;
623
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700624 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700625 const String8 mVsyncOnLabel;
626 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700627
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700628 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700629
630 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800631 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700632
633 Mutex mVsyncMutex; // Protects the following
634 nsecs_t mPhaseOffset;
635 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700636};
637
Lloyd Piquee83f9312018-02-01 12:53:17 -0800638class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700639public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800640 InjectVSyncSource() = default;
641 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700642
Lloyd Piquee83f9312018-02-01 12:53:17 -0800643 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700644 std::lock_guard<std::mutex> lock(mCallbackMutex);
645 mCallback = callback;
646 }
647
Lloyd Piquee83f9312018-02-01 12:53:17 -0800648 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700649 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700650 if (mCallback) {
651 mCallback->onVSyncEvent(when);
652 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700653 }
654
Lloyd Piquee83f9312018-02-01 12:53:17 -0800655 void setVSyncEnabled(bool) override {}
656 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700657
658private:
659 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800660 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700661};
662
Wei Wangf9b05ee2017-07-19 20:59:39 -0700663// Do not call property_set on main thread which will be blocked by init
664// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700665void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700666 ALOGI( "SurfaceFlinger's main thread ready to run. "
667 "Initializing graphics H/W...");
668
Thierry Strudel2924d012017-08-14 15:19:37 -0700669 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900670
Steven Thomasb02664d2017-07-26 18:48:28 -0700671 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800672
Steven Thomasb02664d2017-07-26 18:48:28 -0700673 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800674 mEventThreadSource =
675 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
676 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800677 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700678 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800679 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800680 "appEventThread");
681 mSfEventThreadSource =
682 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
683 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800684
Lloyd Pique24b0a482018-03-09 18:52:26 -0800685 mSFEventThread =
686 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700687 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800688 [this](nsecs_t timestamp) {
689 mInterceptor->saveVSyncEvent(timestamp);
690 },
691 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800692 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200693 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800694
Steven Thomasb02664d2017-07-26 18:48:28 -0700695 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800696 getBE().mRenderEngine =
697 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
698 hasWideColorDisplay
699 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
700 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800701 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700702
703 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
704 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800705 getBE().mHwc.reset(
706 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700707 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800708 // Process any initial hotplug and resulting display changes.
709 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700710 const auto display = getDefaultDisplayDeviceLocked();
711 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
712 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
713 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800714
Lloyd Piquefcd86612017-12-14 17:15:36 -0800715 // make the default display GLContext current so that we can create textures
716 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700717 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800718
Steven Thomas050b2c82017-03-06 11:45:16 -0800719 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700720 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700721 // This callback is called from the vr flinger dispatch thread. We
722 // need to call signalTransaction(), which requires holding
723 // mStateLock when we're not on the main thread. Acquiring
724 // mStateLock from the vr flinger dispatch thread might trigger a
725 // deadlock in surface flinger (see b/66916578), so post a message
726 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700727 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700728 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
729 mVrFlingerRequestsDisplay = requestDisplay;
730 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700731 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800732 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700733 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
734 getHwComposer()
735 .getHwcDisplayId(display->getId())
736 .value_or(0),
737 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800738 if (!mVrFlinger) {
739 ALOGE("Failed to start vrflinger");
740 }
741 }
742
Lloyd Pique379adc12018-01-22 17:31:47 -0800743 mEventControlThread = std::make_unique<impl::EventControlThread>(
744 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700745
Mathias Agopian92a979a2012-08-02 18:32:23 -0700746 // initialize our drawing state
747 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700748
Andy McFadden13a082e2012-08-24 10:16:42 -0700749 // set initial conditions (e.g. unblank default device)
750 initializeDisplays();
751
David Sodmanbc815282017-11-05 18:57:52 -0800752 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700753
Wei Wangf9b05ee2017-07-19 20:59:39 -0700754 // Inform native graphics APIs whether the present timestamp is supported:
755 if (getHwComposer().hasCapability(
756 HWC2::Capability::PresentFenceIsNotReliable)) {
757 mStartPropertySetThread = new StartPropertySetThread(false);
758 } else {
759 mStartPropertySetThread = new StartPropertySetThread(true);
760 }
761
762 if (mStartPropertySetThread->Start() != NO_ERROR) {
763 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800764 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800765
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700766 mLegacySrgbSaturationMatrix =
767 getHwComposer().getDataspaceSaturationMatrix(display->getId(), Dataspace::SRGB_LINEAR);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800768
Dan Stoza9e56aa02015-11-02 13:00:03 -0800769 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700770}
771
Romain Guy11d63f42017-07-20 12:47:14 -0700772void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700773 Mutex::Autolock _l(mStateLock);
774
Romain Guy11d63f42017-07-20 12:47:14 -0700775 char value[PROPERTY_VALUE_MAX];
776
777 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800778 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700779 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800780 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100781
782 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700783 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700784}
785
Mathias Agopiana67e4182012-06-19 17:26:12 -0700786void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800787 // Start boot animation service by setting a property mailbox
788 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700789 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800790 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700791 if (mStartPropertySetThread->join() != NO_ERROR) {
792 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800793 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700794}
795
Mathias Agopian875d8e12013-06-07 15:35:48 -0700796size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800797 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700798}
799
Mathias Agopian875d8e12013-06-07 15:35:48 -0700800size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800801 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700802}
803
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800804// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800805
Jamie Gennis582270d2011-08-17 18:19:00 -0700806bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800807 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800808 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800809 return authenticateSurfaceTextureLocked(bufferProducer);
810}
811
812bool SurfaceFlinger::authenticateSurfaceTextureLocked(
813 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800814 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800815 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800816}
817
Brian Anderson6b376712017-04-04 10:51:39 -0700818status_t SurfaceFlinger::getSupportedFrameTimestamps(
819 std::vector<FrameEvent>* outSupported) const {
820 *outSupported = {
821 FrameEvent::REQUESTED_PRESENT,
822 FrameEvent::ACQUIRE,
823 FrameEvent::LATCH,
824 FrameEvent::FIRST_REFRESH_START,
825 FrameEvent::LAST_REFRESH_START,
826 FrameEvent::GPU_COMPOSITION_DONE,
827 FrameEvent::DEQUEUE_READY,
828 FrameEvent::RELEASE,
829 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700830 ConditionalLock _l(mStateLock,
831 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700832 if (!getHwComposer().hasCapability(
833 HWC2::Capability::PresentFenceIsNotReliable)) {
834 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
835 }
836 return NO_ERROR;
837}
838
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700839status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
840 Vector<DisplayInfo>* configs) {
841 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 return BAD_VALUE;
843 }
844
Jesse Hall692c7232012-11-08 15:41:56 -0800845 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700846 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
847 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700848 type = i;
849 break;
850 }
851 }
852
853 if (type < 0) {
854 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700855 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700856
Mathias Agopian8b736f12012-08-13 17:54:26 -0700857 // TODO: Not sure if display density should handled by SF any longer
858 class Density {
859 static int getDensityFromProperty(char const* propName) {
860 char property[PROPERTY_VALUE_MAX];
861 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800862 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700863 density = atoi(property);
864 }
865 return density;
866 }
867 public:
868 static int getEmuDensity() {
869 return getDensityFromProperty("qemu.sf.lcd_density"); }
870 static int getBuildDensity() {
871 return getDensityFromProperty("ro.sf.lcd_density"); }
872 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700873
Dan Stoza7f7da322014-05-02 15:26:25 -0700874 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700875
Steven Thomas6d8110b2017-08-31 18:24:21 -0700876 ConditionalLock _l(mStateLock,
877 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800878 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700879 DisplayInfo info = DisplayInfo();
880
Dan Stoza9e56aa02015-11-02 13:00:03 -0800881 float xdpi = hwConfig->getDpiX();
882 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700883
884 if (type == DisplayDevice::DISPLAY_PRIMARY) {
885 // The density of the device is provided by a build property
886 float density = Density::getBuildDensity() / 160.0f;
887 if (density == 0) {
888 // the build doesn't provide a density -- this is wrong!
889 // use xdpi instead
890 ALOGE("ro.sf.lcd_density must be defined as a build property");
891 density = xdpi / 160.0f;
892 }
893 if (Density::getEmuDensity()) {
894 // if "qemu.sf.lcd_density" is specified, it overrides everything
895 xdpi = ydpi = density = Density::getEmuDensity();
896 density /= 160.0f;
897 }
898 info.density = density;
899
900 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700901 const auto display = getDefaultDisplayDeviceLocked();
902 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700903 } else {
904 // TODO: where should this value come from?
905 static const int TV_DENSITY = 213;
906 info.density = TV_DENSITY / 160.0f;
907 info.orientation = 0;
908 }
909
Dan Stoza9e56aa02015-11-02 13:00:03 -0800910 info.w = hwConfig->getWidth();
911 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700912 info.xdpi = xdpi;
913 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800914 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900915 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800916
Andy McFadden91b2ca82014-06-13 14:04:23 -0700917 // This is how far in advance a buffer must be queued for
918 // presentation at a given time. If you want a buffer to appear
919 // on the screen at time N, you must submit the buffer before
920 // (N - presentationDeadline).
921 //
922 // Normally it's one full refresh period (to give SF a chance to
923 // latch the buffer), but this can be reduced by configuring a
924 // DispSync offset. Any additional delays introduced by the hardware
925 // composer or panel must be accounted for here.
926 //
927 // We add an additional 1ms to allow for processing time and
928 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800929 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800930 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700931
932 // All non-virtual displays are currently considered secure.
933 info.secure = true;
934
Iris Chang7501ed62018-04-30 14:45:42 +0800935 if (type == DisplayDevice::DISPLAY_PRIMARY &&
936 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
937 std::swap(info.w, info.h);
938 }
939
Michael Wright28f24d02016-07-12 13:30:53 -0700940 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700941 }
942
Dan Stoza7f7da322014-05-02 15:26:25 -0700943 return NO_ERROR;
944}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700945
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700946status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
947 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700948 return BAD_VALUE;
949 }
950
951 // FIXME for now we always return stats for the primary display
952 memset(stats, 0, sizeof(*stats));
953 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
954 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
955 return NO_ERROR;
956}
957
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700958int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
959 const auto display = getDisplayDevice(displayToken);
960 if (!display) {
961 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800962 return BAD_VALUE;
963 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700964
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700965 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700966}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700967
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700968void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
969 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700970 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700971 return;
972 }
973
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700974 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700975 ALOGW("Trying to set config for virtual display");
976 return;
977 }
978
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700979 display->setActiveConfig(mode);
980 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700981}
982
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700983status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700984 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700985 Vector<DisplayInfo> configs;
986 getDisplayConfigs(displayToken, &configs);
987 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
988 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
989 configs.size());
990 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700991 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700992 const auto display = getDisplayDevice(displayToken);
993 if (!display) {
994 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
995 displayToken.get());
996 } else if (display->isVirtual()) {
997 ALOGW("Attempt to set active config %d for virtual display", mode);
998 } else {
999 setActiveConfigInternal(display, mode);
1000 }
1001 }));
1002
Mathias Agopian888c8222012-08-04 21:10:38 -07001003 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001004}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001005status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1006 Vector<ColorMode>* outColorModes) {
1007 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001008 return BAD_VALUE;
1009 }
1010
Michael Wright28f24d02016-07-12 13:30:53 -07001011 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001012 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1013 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001014 type = i;
1015 break;
1016 }
1017 }
1018
1019 if (type < 0) {
1020 return type;
1021 }
1022
Peiyong Lina52f0292018-03-14 17:26:31 -07001023 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001024 {
1025 ConditionalLock _l(mStateLock,
1026 std::this_thread::get_id() != mMainThreadId);
1027 modes = getHwComposer().getColorModes(type);
1028 }
Michael Wright28f24d02016-07-12 13:30:53 -07001029 outColorModes->clear();
1030 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1031
1032 return NO_ERROR;
1033}
1034
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001035ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1036 if (const auto display = getDisplayDevice(displayToken)) {
1037 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001038 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001039 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001040}
1041
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001042void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1043 Dataspace dataSpace, RenderIntent renderIntent) {
1044 ColorMode currentMode = display->getActiveColorMode();
1045 Dataspace currentDataSpace = display->getCompositionDataSpace();
1046 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001047
Peiyong Lin38e9a562018-04-10 16:24:20 -07001048 if (mode == currentMode && dataSpace == currentDataSpace &&
1049 renderIntent == currentRenderIntent) {
1050 return;
1051 }
1052
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001053 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001054 ALOGW("Trying to set config for virtual display");
1055 return;
1056 }
1057
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058 display->setActiveColorMode(mode);
1059 display->setCompositionDataSpace(dataSpace);
1060 display->setActiveRenderIntent(renderIntent);
1061 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001062
1063 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001064 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1065 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001066}
1067
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001068status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001069 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001070 Vector<ColorMode> modes;
1071 getDisplayColorModes(displayToken, &modes);
1072 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1073 if (mode < ColorMode::NATIVE || !exists) {
1074 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1075 decodeColorMode(mode).c_str(), mode, displayToken.get());
1076 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001077 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001078 const auto display = getDisplayDevice(displayToken);
1079 if (!display) {
1080 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1081 decodeColorMode(mode).c_str(), mode, displayToken.get());
1082 } else if (display->isVirtual()) {
1083 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1084 decodeColorMode(mode).c_str(), mode);
1085 } else {
1086 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1087 RenderIntent::COLORIMETRIC);
1088 }
1089 }));
1090
Michael Wright28f24d02016-07-12 13:30:53 -07001091 return NO_ERROR;
1092}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001093
Svetoslavd85084b2014-03-20 10:28:31 -07001094status_t SurfaceFlinger::clearAnimationFrameStats() {
1095 Mutex::Autolock _l(mStateLock);
1096 mAnimFrameTracker.clearStats();
1097 return NO_ERROR;
1098}
1099
1100status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1101 Mutex::Autolock _l(mStateLock);
1102 mAnimFrameTracker.getStats(outStats);
1103 return NO_ERROR;
1104}
1105
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001106status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1107 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001108 Mutex::Autolock _l(mStateLock);
1109
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001110 const auto display = getDisplayDeviceLocked(displayToken);
1111 if (!display) {
1112 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001113 return BAD_VALUE;
1114 }
1115
Peiyong Linfb069302018-04-25 14:34:31 -07001116 // At this point the DisplayDeivce should already be set up,
1117 // meaning the luminance information is already queried from
1118 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001119 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001120 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1121 capabilities.getDesiredMaxLuminance(),
1122 capabilities.getDesiredMaxAverageLuminance(),
1123 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001124
1125 return NO_ERROR;
1126}
1127
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001128status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001129 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001130 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001131
Chia-I Wu90f669f2017-10-05 14:24:41 -07001132 if (mInjectVSyncs == enable) {
1133 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001134 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001135
1136 if (enable) {
1137 ALOGV("VSync Injections enabled");
1138 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001139 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001140 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001141 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001142 impl::EventThread::InterceptVSyncsCallback(),
1143 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001144 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001145 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001146 } else {
1147 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001148 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001149 }
1150
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001151 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001152 }));
1153
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001154 return NO_ERROR;
1155}
1156
1157status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001158 Mutex::Autolock _l(mStateLock);
1159
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001160 if (!mInjectVSyncs) {
1161 ALOGE("VSync Injections not enabled");
1162 return BAD_VALUE;
1163 }
1164 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1165 ALOGV("Injecting VSync inside SurfaceFlinger");
1166 mVSyncInjector->onInjectSyncEvent(when);
1167 }
1168 return NO_ERROR;
1169}
1170
Lloyd Pique755e3192018-01-31 16:46:15 -08001171status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1172 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001173 IPCThreadState* ipc = IPCThreadState::self();
1174 const int pid = ipc->getCallingPid();
1175 const int uid = ipc->getCallingUid();
1176 if ((uid != AID_SHELL) &&
1177 !PermissionCache::checkPermission(sDump, pid, uid)) {
1178 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1179 return PERMISSION_DENIED;
1180 }
1181
1182 // Try to acquire a lock for 1s, fail gracefully
1183 const status_t err = mStateLock.timedLock(s2ns(1));
1184 const bool locked = (err == NO_ERROR);
1185 if (!locked) {
1186 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1187 return TIMED_OUT;
1188 }
1189
1190 outLayers->clear();
1191 mCurrentState.traverseInZOrder([&](Layer* layer) {
1192 outLayers->push_back(layer->getLayerDebugInfo());
1193 });
1194
1195 mStateLock.unlock();
1196 return NO_ERROR;
1197}
1198
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001199// ----------------------------------------------------------------------------
1200
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001201sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1202 ISurfaceComposer::VsyncSource vsyncSource) {
1203 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1204 return mSFEventThread->createEventConnection();
1205 } else {
1206 return mEventThread->createEventConnection();
1207 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001208}
1209
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001210// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001211
1212void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001213 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001214}
1215
1216void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001217 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001218}
1219
1220void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001221 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001222}
1223
1224void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001225 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001226 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001227}
1228
1229status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001230 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001231 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001232}
1233
1234status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001235 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001236 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001237 if (res == NO_ERROR) {
1238 msg->wait();
1239 }
1240 return res;
1241}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001242
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001243void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001244 do {
1245 waitForEvent();
1246 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001247}
1248
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001249void SurfaceFlinger::enableHardwareVsync() {
1250 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001251 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001252 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001253 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001255 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256}
1257
Jesse Hall948fe0c2013-10-14 12:56:09 -07001258void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001259 Mutex::Autolock _l(mHWVsyncLock);
1260
Jesse Hall948fe0c2013-10-14 12:56:09 -07001261 if (makeAvailable) {
1262 mHWVsyncAvailable = true;
1263 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001264 // Hardware vsync is not currently available, so abort the resync
1265 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001266 return;
1267 }
1268
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001269 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1270 if (!getHwComposer().isConnected(displayId)) {
1271 return;
1272 }
1273
1274 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001275 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001276
1277 mPrimaryDispSync.reset();
1278 mPrimaryDispSync.setPeriod(period);
1279
1280 if (!mPrimaryHWVsyncEnabled) {
1281 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001282 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001283 mPrimaryHWVsyncEnabled = true;
1284 }
1285}
1286
Jesse Hall948fe0c2013-10-14 12:56:09 -07001287void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288 Mutex::Autolock _l(mHWVsyncLock);
1289 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001290 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001291 mPrimaryDispSync.endResync();
1292 mPrimaryHWVsyncEnabled = false;
1293 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001294 if (makeUnavailable) {
1295 mHWVsyncAvailable = false;
1296 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297}
1298
Tim Murray4a4e4a22016-04-19 16:29:23 +00001299void SurfaceFlinger::resyncWithRateLimit() {
1300 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001301
1302 // No explicit locking is needed here since EventThread holds a lock while calling this method
1303 static nsecs_t sLastResyncAttempted = 0;
1304 const nsecs_t now = systemTime();
1305 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001306 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001307 }
Dan Stoza57164302017-05-08 14:03:54 -07001308 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001309}
1310
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001311void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1312 int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001313 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001314 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001315 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001316 return;
1317 }
1318
1319 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001320 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001321 return;
1322 }
1323
Jamie Gennisd1700752013-10-14 12:22:52 -07001324 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001325
Jamie Gennisd1700752013-10-14 12:22:52 -07001326 { // Scope for the lock
1327 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001328 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001329 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001330 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001331 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001332
1333 if (needsHwVsync) {
1334 enableHardwareVsync();
1335 } else {
1336 disableHardwareVsync(false);
1337 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001338}
1339
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001340void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001341 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1342 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001343}
1344
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001345void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001346 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001347 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001348 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001349
Lloyd Piqueba04e622017-12-14 17:11:26 -08001350 // Ignore events that do not have the right sequenceId.
1351 if (sequenceId != getBE().mComposerSequenceId) {
1352 return;
1353 }
1354
Steven Thomasb02664d2017-07-26 18:48:28 -07001355 // Only lock if we're not on the main thread. This function is normally
1356 // called on a hwbinder thread, but for the primary display it's called on
1357 // the main thread with the state lock already held, so don't attempt to
1358 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001359 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001360
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001361 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001362
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001363 if (std::this_thread::get_id() == mMainThreadId) {
1364 // Process all pending hot plug events immediately if we are on the main thread.
1365 processDisplayHotplugEventsLocked();
1366 }
1367
Lloyd Piqueba04e622017-12-14 17:11:26 -08001368 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001369}
1370
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001371void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001372 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001373 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001374 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001375 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001376 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001377}
1378
Dan Stoza9e56aa02015-11-02 13:00:03 -08001379void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001380 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001381 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001382 getHwComposer().setVsyncEnabled(disp,
1383 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001384}
1385
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001386// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001387void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001388 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001389 // Clear the drawing state so that the logic inside of
1390 // handleTransactionLocked will fire. It will determine the delta between
1391 // mCurrentState and mDrawingState and re-apply all changes when we make the
1392 // transition.
1393 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001394 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001395 mDisplays.clear();
1396}
1397
Steven Thomas050b2c82017-03-06 11:45:16 -08001398void SurfaceFlinger::updateVrFlinger() {
1399 if (!mVrFlinger)
1400 return;
1401 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001402 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001403 return;
1404 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001405
David Sodman105b7dc2017-11-04 20:28:14 -07001406 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 ALOGE("Vr flinger is only supported for remote hardware composer"
1408 " service connections. Ignoring request to transition to vr"
1409 " flinger.");
1410 mVrFlingerRequestsDisplay = false;
1411 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001412 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001413
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001414 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001415
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001416 const auto display = getDefaultDisplayDeviceLocked();
1417 LOG_ALWAYS_FATAL_IF(!display);
1418 const int currentDisplayPowerMode = display->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Steven Thomasb02664d2017-07-26 18:48:28 -07001420 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001421 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001423
Steven Thomasb02664d2017-07-26 18:48:28 -07001424 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001425 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001426 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1427 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001428 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001429
David Sodman105b7dc2017-11-04 20:28:14 -07001430 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1431 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001432
1433 if (vrFlingerRequestsDisplay) {
1434 mVrFlinger->GrantDisplayOwnership();
1435 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001436 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001437 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001438
1439 mVisibleRegionsDirty = true;
1440 invalidateHwcGeometry();
1441
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001442 // Re-enable default display.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001443 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001444
Steven Thomasb02664d2017-07-26 18:48:28 -07001445 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001446 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001447 const nsecs_t period = activeConfig->getVsyncPeriod();
1448 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001449
Steven Thomasb02664d2017-07-26 18:48:28 -07001450 // Use phase of 0 since phase is not known.
1451 // Use latency of 0, which will snap to the ideal latency.
1452 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001453
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001454 android_atomic_or(1, &mRepaintEverything);
1455 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001456}
1457
Mathias Agopian4fec8732012-06-29 14:12:52 -07001458void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001459 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001460 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001461 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001462 bool frameMissed = !mHadClientComposition &&
1463 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001464 (mPreviousPresentFence->getSignalTime() ==
1465 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001466 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001467 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001468 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001469 mTimeStats.incrementMissedFrames();
1470 if (mPropagateBackpressure) {
1471 signalLayerUpdate();
1472 break;
1473 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001474 }
Dan Stoza50182882016-07-08 12:02:20 -07001475
Steven Thomas050b2c82017-03-06 11:45:16 -08001476 // Now that we're going to make it to the handleMessageTransaction()
1477 // call below it's safe to call updateVrFlinger(), which will
1478 // potentially trigger a display handoff.
1479 updateVrFlinger();
1480
Dan Stoza6b9454d2014-11-07 16:00:59 -08001481 bool refreshNeeded = handleMessageTransaction();
1482 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001483 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001484 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001485 // Signal a refresh if a transaction modified the window state,
1486 // a new buffer was latched, or if HWC has requested a full
1487 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001488 signalRefresh();
1489 }
1490 break;
1491 }
1492 case MessageQueue::REFRESH: {
1493 handleMessageRefresh();
1494 break;
1495 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001496 }
1497}
1498
Dan Stoza6b9454d2014-11-07 16:00:59 -08001499bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001500 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001501 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001502 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001503 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001504 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001505 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001506}
1507
Dan Stoza6b9454d2014-11-07 16:00:59 -08001508bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001509 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001510 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001511}
1512
1513void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001514 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001515
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001516 mRefreshPending = false;
1517
Chia-I Wu30505fb2018-03-26 16:20:31 -07001518 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001519
Chia-I Wu30505fb2018-03-26 16:20:31 -07001520 preComposition(refreshStartTime);
1521 rebuildLayerStacks();
1522 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001523 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001524 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001525 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001526 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001527 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001528
Dan Stozabfbffeb2016-07-21 14:49:33 -07001529 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001530 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001531 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001532 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001533 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001534 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001535
Dan Stoza9e56aa02015-11-02 13:00:03 -08001536 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001537}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001538
Mathias Agopiancd60f992012-08-16 16:28:27 -07001539void SurfaceFlinger::doDebugFlashRegions()
1540{
1541 // is debugging enabled
1542 if (CC_LIKELY(!mDebugRegion))
1543 return;
1544
1545 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001546 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001547 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001548 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001549 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001550 if (!dirtyRegion.isEmpty()) {
1551 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001552 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001553
1554 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001555 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001556 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001557 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1558
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001559 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560 }
1561 }
1562 }
1563
1564 postFramebuffer();
1565
1566 if (mDebugRegion > 1) {
1567 usleep(mDebugRegion * 1000);
1568 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001569
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001570 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001571 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001572 continue;
1573 }
1574
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001575 status_t result = display->prepareFrame(*getBE().mHwc);
1576 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001577 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001578 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001579}
1580
Adrian Roos1e1a1282017-11-01 19:05:31 +01001581void SurfaceFlinger::doTracing(const char* where) {
1582 ATRACE_CALL();
1583 ATRACE_NAME(where);
1584 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001585 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001586 }
1587}
1588
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001589void SurfaceFlinger::logLayerStats() {
1590 ATRACE_CALL();
1591 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001592 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001593 if (display->isPrimary()) {
1594 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001595 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001596 }
1597 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001598
1599 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001600 }
1601}
1602
Chia-I Wu30505fb2018-03-26 16:20:31 -07001603void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001604{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001605 ATRACE_CALL();
1606 ALOGV("preComposition");
1607
Mathias Agopiancd60f992012-08-16 16:28:27 -07001608 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001609 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001610 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001611 needExtraInvalidate = true;
1612 }
Robert Carr2047fae2016-11-28 14:09:09 -08001613 });
1614
Mathias Agopiancd60f992012-08-16 16:28:27 -07001615 if (needExtraInvalidate) {
1616 signalLayerUpdate();
1617 }
1618}
1619
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001620void SurfaceFlinger::updateCompositorTiming(
1621 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1622 std::shared_ptr<FenceTime>& presentFenceTime) {
1623 // Update queue of past composite+present times and determine the
1624 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001625 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001626 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001627 while (!getBE().mCompositePresentTimes.empty()) {
1628 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001629 // Cached values should have been updated before calling this method,
1630 // which helps avoid duplicate syscalls.
1631 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1632 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1633 break;
1634 }
1635 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001636 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001637 }
1638
1639 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001640 while (getBE().mCompositePresentTimes.size() > 16) {
1641 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001642 }
1643
Brian Andersond0010582017-03-07 13:20:31 -08001644 setCompositorTimingSnapped(
1645 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1646}
1647
1648void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1649 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650 // Integer division and modulo round toward 0 not -inf, so we need to
1651 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001652 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001653 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1654 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1655
Brian Andersond0010582017-03-07 13:20:31 -08001656 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1657 if (idealLatency <= 0) {
1658 idealLatency = vsyncInterval;
1659 }
1660
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001661 // Snap the latency to a value that removes scheduling jitter from the
1662 // composition and present times, which often have >1ms of jitter.
1663 // Reducing jitter is important if an app attempts to extrapolate
1664 // something (such as user input) to an accurate diasplay time.
1665 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1666 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001667 nsecs_t bias = vsyncInterval / 2;
1668 int64_t extraVsyncs =
1669 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1670 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1671 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001672
David Sodman99974d22017-11-28 12:04:33 -08001673 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1674 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1675 getBE().mCompositorTiming.interval = vsyncInterval;
1676 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001677}
1678
Chia-I Wu30505fb2018-03-26 16:20:31 -07001679void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001680{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001681 ATRACE_CALL();
1682 ALOGV("postComposition");
1683
Brian Anderson3546a3f2016-07-14 11:51:14 -07001684 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001685 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001686 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001687 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001688 }
1689
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001690 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001691 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001692
David Sodman73beded2017-11-15 11:56:06 -08001693 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001694 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001695 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001696 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001697 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001698 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001699 } else {
1700 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1701 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001702
David Sodman73beded2017-11-15 11:56:06 -08001703 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001704 mPreviousPresentFence =
1705 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1706 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001707 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001708
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001709 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1710 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1711
Chia-I Wu30505fb2018-03-26 16:20:31 -07001712 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001713 // when we started doing work for this frame, but that should be okay
1714 // since updateCompositorTiming has snapping logic.
1715 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001716 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001717 CompositorTiming compositorTiming;
1718 {
David Sodman99974d22017-11-28 12:04:33 -08001719 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1720 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001721 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001722
Robert Carr2047fae2016-11-28 14:09:09 -08001723 mDrawingState.traverseInZOrder([&](Layer* layer) {
1724 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001725 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001726 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001727 recordBufferingStats(layer->getName().string(),
1728 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001729 }
Robert Carr2047fae2016-11-28 14:09:09 -08001730 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001731
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001732 if (presentFenceTime->isValid()) {
1733 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001734 enableHardwareVsync();
1735 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001736 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001737 }
1738 }
1739
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001740 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001741 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001742 enableHardwareVsync();
1743 }
1744 }
1745
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001746 if (mAnimCompositionPending) {
1747 mAnimCompositionPending = false;
1748
Brian Anderson4e606e32017-03-16 15:34:57 -07001749 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001750 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001751 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001752 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001753 // The HWC doesn't support present fences, so use the refresh
1754 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001755 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001756 mAnimFrameTracker.setActualPresentTime(presentTime);
1757 }
1758 mAnimFrameTracker.advanceFrame();
1759 }
Dan Stozab90cf072015-03-05 11:05:59 -08001760
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001761 mTimeStats.incrementTotalFrames();
1762 if (mHadClientComposition) {
1763 mTimeStats.incrementClientCompositionFrames();
1764 }
1765
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001766 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001767 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001768 return;
1769 }
1770
1771 nsecs_t currentTime = systemTime();
1772 if (mHasPoweredOff) {
1773 mHasPoweredOff = false;
1774 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001775 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001776 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001777 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1778 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001779 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001780 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001781 }
David Sodman4a36e932017-11-07 14:29:47 -08001782 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001783 }
David Sodman4a36e932017-11-07 14:29:47 -08001784 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001785
1786 {
1787 std::lock_guard lock(mTexturePoolMutex);
1788 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1789 if (refillCount > 0) {
1790 const size_t offset = mTexturePool.size();
1791 mTexturePool.resize(mTexturePoolSize);
1792 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1793 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1794 }
1795 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001796}
1797
1798void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001799 ATRACE_CALL();
1800 ALOGV("rebuildLayerStacks");
1801
Mathias Agopiancd60f992012-08-16 16:28:27 -07001802 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001803 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001804 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001805 mVisibleRegionsDirty = false;
1806 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001807
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001808 for (const auto& pair : mDisplays) {
1809 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001810 Region opaqueRegion;
1811 Region dirtyRegion;
1812 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001813 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001814 const Transform& tr = display->getTransform();
1815 const Rect bounds = display->getBounds();
1816 if (display->isPoweredOn()) {
1817 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001818
Jeff Sharkey76488112017-02-27 14:15:18 -07001819 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001820 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001821 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001822 Region drawRegion(tr.transform(
1823 layer->visibleNonTransparentRegion));
1824 drawRegion.andSelf(bounds);
1825 if (!drawRegion.isEmpty()) {
1826 layersSortedByZ.add(layer);
1827 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001828 // Clear out the HWC layer if this layer was
1829 // previously visible, but no longer is
Dominik Laskowski7e045462018-05-30 13:02:02 -07001830 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001831 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001832 } else {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001833 // WM changes display->layerStack upon sleep/awake.
Chia-I Wu30505fb2018-03-26 16:20:31 -07001834 // Here we make sure we delete the HWC layers even if
1835 // WM changed their layer stack.
Dominik Laskowski7e045462018-05-30 13:02:02 -07001836 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001837 }
1838
1839 // If a layer is not going to get a release fence because
1840 // it is invisible, but it is also going to release its
1841 // old buffer, add it to the list of layers needing
1842 // fences.
1843 if (hwcLayerDestroyed) {
1844 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1845 mLayersWithQueuedFrames.cend(), layer);
1846 if (found != mLayersWithQueuedFrames.cend()) {
1847 layersNeedingFences.add(layer);
1848 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001849 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001850 });
1851 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001852 display->setVisibleLayersSortedByZ(layersSortedByZ);
1853 display->setLayersNeedingFences(layersNeedingFences);
1854 display->undefinedRegion.set(bounds);
1855 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1856 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001857 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001858 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001859}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001860
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001861// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001862// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001863// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001864// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001865// The returned HDR data space is one of
1866// - Dataspace::UNKNOWN
1867// - Dataspace::BT2020_HLG
1868// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001869Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1870 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001871 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001872 *outHdrDataSpace = Dataspace::UNKNOWN;
1873
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001874 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001875 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001876 case Dataspace::V0_SCRGB:
1877 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001878 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001879 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001880 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001881 case Dataspace::BT2020_PQ:
1882 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001883 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001884 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001885 case Dataspace::BT2020_HLG:
1886 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001887 // When there's mixed PQ content and HLG content, we set the HDR
1888 // data space to be BT2020_PQ and convert HLG to PQ.
1889 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1890 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001891 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001892 break;
1893 default:
1894 break;
1895 }
Romain Guy54f154a2017-10-24 21:40:32 +01001896 }
1897
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001898 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001899}
1900
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001901// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001902void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1903 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001904 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1905 *outMode = ColorMode::NATIVE;
1906 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001907 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001908 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001909 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001910
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001911 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001912 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001913
Peiyong Lindfde5112018-06-05 10:58:41 -07001914 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001915 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001916 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001917 if (isHdr) {
1918 bestDataSpace = hdrDataSpace;
1919 }
1920
Chia-I Wu0d711262018-05-21 15:19:35 -07001921 RenderIntent intent;
1922 switch (mDisplayColorSetting) {
1923 case DisplayColorSetting::MANAGED:
1924 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001925 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001926 break;
1927 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001928 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001929 break;
1930 default: // vendor display color setting
1931 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1932 break;
1933 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001934
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001935 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001936}
1937
Chia-I Wu30505fb2018-03-26 16:20:31 -07001938void SurfaceFlinger::setUpHWComposer() {
1939 ATRACE_CALL();
1940 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001941
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001942 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001943 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
1944 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1945 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07001946
1947 // If nothing has changed (!dirty), don't recompose.
1948 // If something changed, but we don't currently have any visible layers,
1949 // and didn't when we last did a composition, then skip it this time.
1950 // The second rule does two things:
1951 // - When all layers are removed from a display, we'll emit one black
1952 // frame, then nothing more until we get new layers.
1953 // - When a display is created with a private layer stack, we won't
1954 // emit any black frames until a layer is added to the layer stack.
1955 bool mustRecompose = dirty && !(empty && wasEmpty);
1956
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001957 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001958 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
1959 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07001960
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001961 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001962
1963 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001964 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07001965 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001966 }
1967
Chia-I Wu30505fb2018-03-26 16:20:31 -07001968 // build the h/w work list
1969 if (CC_UNLIKELY(mGeometryInvalid)) {
1970 mGeometryInvalid = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001971 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001972 const auto displayId = display->getId();
1973 if (displayId >= 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001974 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001975 for (size_t i = 0; i < currentLayers.size(); i++) {
1976 const auto& layer = currentLayers[i];
Dominik Laskowski7e045462018-05-30 13:02:02 -07001977 if (!layer->hasHwcLayer(displayId)) {
1978 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1979 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001980 continue;
1981 }
1982 }
1983
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001984 layer->setGeometry(display, i);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001985 if (mDebugDisableHWC || mDebugRegion) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001986 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001987 }
1988 }
1989 }
1990 }
1991 }
1992
Chia-I Wu30505fb2018-03-26 16:20:31 -07001993 // Set the per-frame data
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001994 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001995 const auto displayId = display->getId();
1996 if (displayId < 0) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001997 continue;
1998 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07001999
Chia-I Wu28f320b2018-05-03 11:02:56 -07002000 if (mDrawingState.colorMatrixChanged) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002001 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002002 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002003 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002004 displayId, result);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002005 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002006 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu692e0832018-06-05 15:46:58 -07002007 if (layer->isHdrY410()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002008 layer->forceClientComposition(displayId);
Chia-I Wu692e0832018-06-05 15:46:58 -07002009 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2010 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
2011 !display->hasHDR10Support()) {
2012 layer->forceClientComposition(displayId);
2013 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2014 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2015 !display->hasHLGSupport()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002016 layer->forceClientComposition(displayId);
Peiyong Linf59a7192018-04-25 11:19:31 -07002017 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002018
Dominik Laskowski7e045462018-05-30 13:02:02 -07002019 if (layer->getForceClientComposition(displayId)) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002020 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002021 layer->setCompositionType(displayId, HWC2::Composition::Client);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002022 continue;
2023 }
2024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002025 layer->setPerFrameData(display);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002026 }
2027
2028 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002029 ColorMode colorMode;
2030 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002031 RenderIntent renderIntent;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002032 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
2033 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002034 }
2035 }
2036
Chia-I Wu28f320b2018-05-03 11:02:56 -07002037 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07002038
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002039 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002040 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002041 continue;
2042 }
2043
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002044 status_t result = display->prepareFrame(*getBE().mHwc);
2045 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002046 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002047 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002048}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002049
Mathias Agopiancd60f992012-08-16 16:28:27 -07002050void SurfaceFlinger::doComposition() {
2051 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002052 ALOGV("doComposition");
2053
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002054 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002055 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002056 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002057 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002058 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002059
2060 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002061 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002062
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002063 display->dirtyRegion.clear();
2064 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002065 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002066 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002067 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002068}
2069
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002070void SurfaceFlinger::postFramebuffer()
2071{
Mathias Agopian841cde52012-03-01 15:44:37 -08002072 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002073 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002074
Mathias Agopiana44b0412011-10-16 18:46:35 -07002075 const nsecs_t now = systemTime();
2076 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002077
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002078 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002079 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002080 continue;
2081 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002082 const auto displayId = display->getId();
2083 if (displayId >= 0) {
2084 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002085 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002086 display->onSwapBuffersCompleted();
2087 display->makeCurrent();
2088 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002089 // The layer buffer from the previous frame (if any) is released
2090 // by HWC only when the release fence from this frame (if any) is
2091 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002092 auto hwcLayer = layer->getHwcLayer(displayId);
2093 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002094
2095 // If the layer was client composited in the previous frame, we
2096 // need to merge with the previous client target acquire fence.
2097 // Since we do not track that, always merge with the current
2098 // client target acquire fence when it is available, even though
2099 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002100 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002101 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002102 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002103 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002104
David Sodmanb8af7922017-12-21 15:17:55 -08002105 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002106 }
Chia-I Wu83806892017-11-16 10:50:20 -08002107
2108 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002109 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002110 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002111 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002112 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002113 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002114 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002115 }
2116 }
2117
Dominik Laskowski7e045462018-05-30 13:02:02 -07002118 if (displayId >= 0) {
2119 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002120 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002121 }
2122
Mathias Agopiana44b0412011-10-16 18:46:35 -07002123 mLastSwapBufferTime = systemTime() - now;
2124 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002125
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002126 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002127 const auto display = getDefaultDisplayDeviceLocked();
2128 if (display && getHwComposer().isConnected(display->getId())) {
2129 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002130 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2131 logFrameStats();
2132 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002133 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002134}
2135
Mathias Agopian87baae12012-07-31 12:38:26 -07002136void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002137{
Mathias Agopian841cde52012-03-01 15:44:37 -08002138 ATRACE_CALL();
2139
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002140 // here we keep a copy of the drawing state (that is the state that's
2141 // going to be overwritten by handleTransactionLocked()) outside of
2142 // mStateLock so that the side-effects of the State assignment
2143 // don't happen with mStateLock held (which can cause deadlocks).
2144 State drawingState(mDrawingState);
2145
Mathias Agopianca4d3602011-05-19 15:38:14 -07002146 Mutex::Autolock _l(mStateLock);
2147 const nsecs_t now = systemTime();
2148 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002149
Mathias Agopianca4d3602011-05-19 15:38:14 -07002150 // Here we're guaranteed that some transaction flags are set
2151 // so we can call handleTransactionLocked() unconditionally.
2152 // We call getTransactionFlags(), which will also clear the flags,
2153 // with mStateLock held to guarantee that mCurrentState won't change
2154 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002155
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002156 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002157 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002158 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002159
Mathias Agopianca4d3602011-05-19 15:38:14 -07002160 mLastTransactionTime = systemTime() - now;
2161 mDebugInTransaction = 0;
2162 invalidateHwcGeometry();
2163 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002164}
2165
Dominik Laskowski7e045462018-05-30 13:02:02 -07002166DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002167 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002168 // Figure out whether the event is for the primary display or an
2169 // external display by matching the Hwc display id against one for a
2170 // connected display. If we did not find a match, we then check what
2171 // displays are not already connected to determine the type. If we don't
2172 // have a connected primary display, we assume the new display is meant to
2173 // be the primary display, and then if we don't have an external display,
2174 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002175 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2176 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002177 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002178 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002179 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002180 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002181 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002182 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002183 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002184 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002185 return DisplayDevice::DISPLAY_EXTERNAL;
2186 }
2187
2188 return DisplayDevice::DISPLAY_ID_INVALID;
2189}
2190
Lloyd Piqueba04e622017-12-14 17:11:26 -08002191void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2192 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002193 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002194 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002195 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002196 continue;
2197 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002198
2199 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2200 ALOGE("External displays are not supported by the vr hardware composer.");
2201 continue;
2202 }
2203
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002204 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002205 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002206 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002207 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002208 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002209
2210 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002211 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002212 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002213 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002214 DisplayDeviceState info;
2215 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002216 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2217 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002218 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002219 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002220 mInterceptor->saveDisplayCreation(info);
2221 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002222 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002223 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002224
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002225 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002226 if (idx >= 0) {
2227 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002228 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002229 mCurrentState.displays.removeItemsAt(idx);
2230 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002231 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002232 }
2233
2234 processDisplayChangesLocked();
2235 }
2236
2237 mPendingHotplugEvents.clear();
2238}
2239
Lloyd Pique99d3da52018-01-22 17:48:03 -08002240sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002241 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002242 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002243 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002244 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002245
Lloyd Pique99d3da52018-01-22 17:48:03 -08002246 if (hasWideColorDisplay) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002247 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002248 for (ColorMode colorMode : modes) {
2249 switch (colorMode) {
2250 case ColorMode::DISPLAY_P3:
2251 case ColorMode::ADOBE_RGB:
2252 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002253 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002254 break;
2255 default:
2256 break;
2257 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002258
Dominik Laskowski7e045462018-05-30 13:02:02 -07002259 std::vector<RenderIntent> renderIntents =
2260 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002261 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002262 }
2263 }
2264
Peiyong Lin62665892018-04-16 11:07:44 -07002265 HdrCapabilities hdrCapabilities;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002266 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002267
2268 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2269 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2270
2271 /*
2272 * Create our display's surface
2273 */
2274 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2275 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002276 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002277 renderSurface->setNativeWindow(nativeWindow.get());
2278 const int displayWidth = renderSurface->queryWidth();
2279 const int displayHeight = renderSurface->queryHeight();
2280
2281 // Make sure that composition can never be stalled by a virtual display
2282 // consumer that isn't processing buffers fast enough. We have to do this
2283 // in two places:
2284 // * Here, in case the display is composed entirely by HWC.
2285 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2286 // window's swap interval in eglMakeCurrent, so they'll override the
2287 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002288 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002289 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2290 }
2291
2292 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002293 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002294
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002295 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002296 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2297 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2298 displayHeight, hasWideColorGamut, hdrCapabilities,
2299 getHwComposer().getSupportedPerFrameMetadata(displayId),
2300 hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002301
2302 if (maxFrameBufferAcquiredBuffers >= 3) {
2303 nativeWindowSurface->preallocateBuffers();
2304 }
2305
2306 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002307 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2308 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002309 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002310 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002311 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002312 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002313 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002314 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002315 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002316 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002317 display->setLayerStack(state.layerStack);
2318 display->setProjection(state.orientation, state.viewport, state.frame);
2319 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002320
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002321 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002322}
2323
Lloyd Pique347200f2017-12-14 17:00:15 -08002324void SurfaceFlinger::processDisplayChangesLocked() {
2325 // here we take advantage of Vector's copy-on-write semantics to
2326 // improve performance by skipping the transaction entirely when
2327 // know that the lists are identical
2328 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2329 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2330 if (!curr.isIdenticalTo(draw)) {
2331 mVisibleRegionsDirty = true;
2332 const size_t cc = curr.size();
2333 size_t dc = draw.size();
2334
2335 // find the displays that were removed
2336 // (ie: in drawing state but not in current state)
2337 // also handle displays that changed
2338 // (ie: displays that are in both lists)
2339 for (size_t i = 0; i < dc;) {
2340 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2341 if (j < 0) {
2342 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002343 // Call makeCurrent() on the primary display so we can
2344 // be sure that nothing associated with this display
2345 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002346 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2347 defaultDisplay->makeCurrent();
2348 }
2349 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2350 display->disconnect(getHwComposer());
2351 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002352 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2353 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2354 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2355 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2356 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002357 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002358 } else {
2359 // this display is in both lists. see if something changed.
2360 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002361 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002362 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2363 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2364 if (state_binder != draw_binder) {
2365 // changing the surface is like destroying and
2366 // recreating the DisplayDevice, so we just remove it
2367 // from the drawing state, so that it get re-added
2368 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002369 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2370 display->disconnect(getHwComposer());
2371 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002372 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002373 mDrawingState.displays.removeItemsAt(i);
2374 dc--;
2375 // at this point we must loop to the next item
2376 continue;
2377 }
2378
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002379 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002380 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002381 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002382 }
2383 if ((state.orientation != draw[i].orientation) ||
2384 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002385 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002386 }
2387 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002388 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002389 }
2390 }
2391 }
2392 ++i;
2393 }
2394
2395 // find displays that were added
2396 // (ie: in current state but not in drawing state)
2397 for (size_t i = 0; i < cc; i++) {
2398 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2399 const DisplayDeviceState& state(curr[i]);
2400
2401 sp<DisplaySurface> dispSurface;
2402 sp<IGraphicBufferProducer> producer;
2403 sp<IGraphicBufferProducer> bqProducer;
2404 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002405 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002406
Dominik Laskowski7e045462018-05-30 13:02:02 -07002407 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002408 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002409 // Virtual displays without a surface are dormant:
2410 // they have external state (layer stack, projection,
2411 // etc.) but no internal state (i.e. a DisplayDevice).
2412 if (state.surface != nullptr) {
2413 // Allow VR composer to use virtual displays.
2414 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2415 int width = 0;
2416 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2417 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2418 int height = 0;
2419 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2420 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2421 int intFormat = 0;
2422 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2423 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002424 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002425
Dominik Laskowski7e045462018-05-30 13:02:02 -07002426 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2427 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002428 }
2429
2430 // TODO: Plumb requested format back up to consumer
2431
2432 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002433 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002434 bqProducer, bqConsumer,
2435 state.displayName);
2436
2437 dispSurface = vds;
2438 producer = vds;
2439 }
2440 } else {
2441 ALOGE_IF(state.surface != nullptr,
2442 "adding a supported display, but rendering "
2443 "surface is provided (%p), ignoring it",
2444 state.surface.get());
2445
Dominik Laskowski7e045462018-05-30 13:02:02 -07002446 displayId = state.type;
2447 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002448 producer = bqProducer;
2449 }
2450
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002451 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002452 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002453 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002454 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002455 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002456 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002457 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2458 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2459 true);
2460 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2461 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2462 true);
2463 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002464 }
2465 }
2466 }
2467 }
2468 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002469
2470 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002471}
2472
Mathias Agopian87baae12012-07-31 12:38:26 -07002473void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002474{
Dan Stoza7dde5992015-05-22 09:51:44 -07002475 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002476 mCurrentState.traverseInZOrder([](Layer* layer) {
2477 layer->notifyAvailableFrames();
2478 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002479
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002480 /*
2481 * Traversal of the children
2482 * (perform the transaction for each of them if needed)
2483 */
2484
Mathias Agopian3559b072012-08-15 13:46:03 -07002485 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002486 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002488 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489
2490 const uint32_t flags = layer->doTransaction(0);
2491 if (flags & Layer::eVisibleRegion)
2492 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002493 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002494 }
2495
2496 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002497 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002498 */
2499
Mathias Agopiane57f2922012-08-09 16:29:12 -07002500 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002501 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002502 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002503 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002505 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002506 // The transform hint might have changed for some layers
2507 // (either because a display has changed, or because a layer
2508 // as changed).
2509 //
2510 // Walk through all the layers in currentLayers,
2511 // and update their transform hint.
2512 //
2513 // If a layer is visible only on a single display, then that
2514 // display is used to calculate the hint, otherwise we use the
2515 // default display.
2516 //
2517 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2518 // the hint is set before we acquire a buffer from the surface texture.
2519 //
2520 // NOTE: layer transactions have taken place already, so we use their
2521 // drawing state. However, SurfaceFlinger's own transaction has not
2522 // happened yet, so we must use the current state layer list
2523 // (soon to become the drawing state list).
2524 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002525 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002526 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002527 bool first = true;
2528 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002529 // NOTE: we rely on the fact that layers are sorted by
2530 // layerStack first (so we don't have to traverse the list
2531 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002532 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002533 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002534 currentlayerStack = layerStack;
2535 // figure out if this layerstack is mirrored
2536 // (more than one display) if so, pick the default display,
2537 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002538 hintDisplay = nullptr;
2539 for (const auto& [token, display] : mDisplays) {
2540 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2541 if (hintDisplay) {
2542 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002543 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002544 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002545 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002546 }
2547 }
2548 }
2549 }
Chet Haase91d25932013-04-11 15:24:55 -07002550
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002551 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002552 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2553 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002554
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002555 // could be null when this layer is using a layerStack
2556 // that is not visible on any display. Also can occur at
2557 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002558 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002559 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002560
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002561 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002562 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002563 if (hintDisplay) {
2564 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002565 }
Robert Carr2047fae2016-11-28 14:09:09 -08002566
2567 first = false;
2568 });
Mathias Agopian84300952012-11-21 16:02:13 -08002569 }
2570
2571
Mathias Agopian3559b072012-08-15 13:46:03 -07002572 /*
2573 * Perform our own transaction if needed
2574 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002575
2576 if (mLayersAdded) {
2577 mLayersAdded = false;
2578 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002579 mVisibleRegionsDirty = true;
2580 }
2581
2582 // some layers might have been removed, so
2583 // we need to update the regions they're exposing.
2584 if (mLayersRemoved) {
2585 mLayersRemoved = false;
2586 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002587 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002588 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002589 // this layer is not visible anymore
2590 // TODO: we could traverse the tree from front to back and
2591 // compute the actual visible region
2592 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002593 Region visibleReg;
2594 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002595 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002596 }
Robert Carr2047fae2016-11-28 14:09:09 -08002597 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598 }
2599
2600 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002601
2602 updateCursorAsync();
2603}
2604
2605void SurfaceFlinger::updateCursorAsync()
2606{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002607 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002608 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002609 continue;
2610 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002611
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002612 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2613 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002614 }
2615 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002616}
2617
2618void SurfaceFlinger::commitTransaction()
2619{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002620 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002621 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002622 for (const auto& l : mLayersPendingRemoval) {
2623 recordBufferingStats(l->getName().string(),
2624 l->getOccupancyHistory(true));
2625 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002626 }
2627 mLayersPendingRemoval.clear();
2628 }
2629
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002630 // If this transaction is part of a window animation then the next frame
2631 // we composite should be considered an animation as well.
2632 mAnimCompositionPending = mAnimTransactionPending;
2633
Mathias Agopian4fec8732012-06-29 14:12:52 -07002634 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002635 // clear the "changed" flags in current state
2636 mCurrentState.colorMatrixChanged = false;
2637
Robert Carr1f0a16a2016-10-24 16:27:39 -07002638 mDrawingState.traverseInZOrder([](Layer* layer) {
2639 layer->commitChildList();
2640 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002641 mTransactionPending = false;
2642 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002643 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002644}
2645
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002646void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2647 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002648 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002649 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002650
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651 Region aboveOpaqueLayers;
2652 Region aboveCoveredLayers;
2653 Region dirty;
2654
Mathias Agopian87baae12012-07-31 12:38:26 -07002655 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656
Robert Carr2047fae2016-11-28 14:09:09 -08002657 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002659 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660
Jesse Hall01e29052013-02-19 16:13:35 -08002661 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002662 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002663 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002664 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002665
Mathias Agopianab028732010-03-16 16:41:46 -07002666 /*
2667 * opaqueRegion: area of a surface that is fully opaque.
2668 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002669 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002670
2671 /*
2672 * visibleRegion: area of a surface that is visible on screen
2673 * and not fully transparent. This is essentially the layer's
2674 * footprint minus the opaque regions above it.
2675 * Areas covered by a translucent surface are considered visible.
2676 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002677 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002678
2679 /*
2680 * coveredRegion: area of a surface that is covered by all
2681 * visible regions above it (which includes the translucent areas).
2682 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002683 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002684
Jesse Halla8026d22012-09-25 13:25:04 -07002685 /*
2686 * transparentRegion: area of a surface that is hinted to be completely
2687 * transparent. This is only used to tell when the layer has no visible
2688 * non-transparent regions and can be removed from the layer list. It
2689 * does not affect the visibleRegion of this layer or any layers
2690 * beneath it. The hint may not be correct if apps don't respect the
2691 * SurfaceView restrictions (which, sadly, some don't).
2692 */
2693 Region transparentRegion;
2694
Mathias Agopianab028732010-03-16 16:41:46 -07002695
2696 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002697 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002698 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002699 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002700 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002701 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002702 if (!visibleRegion.isEmpty()) {
2703 // Remove the transparent area from the visible region
2704 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002705 if (tr.preserveRects()) {
2706 // transform the transparent region
2707 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002708 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002709 // transformation too complex, can't do the
2710 // transparent region optimization.
2711 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002712 }
Mathias Agopianab028732010-03-16 16:41:46 -07002713 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714
Mathias Agopianab028732010-03-16 16:41:46 -07002715 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002716 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002717 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002718 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2719 // the opaque region is the layer's footprint
2720 opaqueRegion = visibleRegion;
2721 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002722 }
2723 }
2724
Robert Carre5f4f692018-01-12 13:12:28 -08002725 if (visibleRegion.isEmpty()) {
2726 layer->clearVisibilityRegions();
2727 return;
2728 }
2729
Mathias Agopianab028732010-03-16 16:41:46 -07002730 // Clip the covered region to the visible region
2731 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2732
2733 // Update aboveCoveredLayers for next (lower) layer
2734 aboveCoveredLayers.orSelf(visibleRegion);
2735
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736 // subtract the opaque region covered by the layers above us
2737 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738
2739 // compute this layer's dirty region
2740 if (layer->contentDirty) {
2741 // we need to invalidate the whole region
2742 dirty = visibleRegion;
2743 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002744 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745 layer->contentDirty = false;
2746 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002747 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002748 * the exposed region consists of two components:
2749 * 1) what's VISIBLE now and was COVERED before
2750 * 2) what's EXPOSED now less what was EXPOSED before
2751 *
2752 * note that (1) is conservative, we start with the whole
2753 * visible region but only keep what used to be covered by
2754 * something -- which mean it may have been exposed.
2755 *
2756 * (2) handles areas that were not covered by anything but got
2757 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002758 */
Mathias Agopianab028732010-03-16 16:41:46 -07002759 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002760 const Region oldVisibleRegion = layer->visibleRegion;
2761 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002762 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2763 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764 }
2765 dirty.subtractSelf(aboveOpaqueLayers);
2766
2767 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002768 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769
Mathias Agopianab028732010-03-16 16:41:46 -07002770 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002772
Jesse Halla8026d22012-09-25 13:25:04 -07002773 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774 layer->setVisibleRegion(visibleRegion);
2775 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002776 layer->setVisibleNonTransparentRegion(
2777 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002778 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779
Mathias Agopian87baae12012-07-31 12:38:26 -07002780 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781}
2782
Chia-I Wuab0c3192017-08-01 11:29:00 -07002783void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002784 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002785 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2786 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002787 }
2788 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002789}
2790
Dan Stoza6b9454d2014-11-07 16:00:59 -08002791bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002793 ALOGV("handlePageFlip");
2794
Brian Andersond6927fb2016-07-23 23:37:30 -07002795 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796
Mathias Agopian4fec8732012-06-29 14:12:52 -07002797 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002798 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002799 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002800
2801 // Store the set of layers that need updates. This set must not change as
2802 // buffers are being latched, as this could result in a deadlock.
2803 // Example: Two producers share the same command stream and:
2804 // 1.) Layer 0 is latched
2805 // 2.) Layer 0 gets a new frame
2806 // 2.) Layer 1 gets a new frame
2807 // 3.) Layer 1 is latched.
2808 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2809 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002810 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002811 if (layer->hasQueuedFrame()) {
2812 frameQueued = true;
2813 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002814 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002815 } else {
2816 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002817 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002818 } else {
2819 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002820 }
Robert Carr2047fae2016-11-28 14:09:09 -08002821 });
2822
Dan Stoza9e56aa02015-11-02 13:00:03 -08002823 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002824 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002825 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002826 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002827 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002828 newDataLatched = true;
2829 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002830 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002831
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002832 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002833
2834 // If we will need to wake up at some time in the future to deal with a
2835 // queued frame that shouldn't be displayed during this vsync period, wake
2836 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002837 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002838 signalLayerUpdate();
2839 }
2840
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002841 // enter boot animation on first buffer latch
2842 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2843 ALOGI("Enter boot animation");
2844 mBootStage = BootStage::BOOTANIMATION;
2845 }
2846
Dan Stoza6b9454d2014-11-07 16:00:59 -08002847 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002848 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849}
2850
Mathias Agopianad456f92011-01-13 17:53:01 -08002851void SurfaceFlinger::invalidateHwcGeometry()
2852{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002853 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002854}
2855
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002856void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2857 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002858 // We only need to actually compose the display if:
2859 // 1) It is being handled by hardware composer, which may need this to
2860 // keep its virtual display state machine in sync, or
2861 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002862 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002863 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002864 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002865 return;
2866 }
2867
Dan Stoza9e56aa02015-11-02 13:00:03 -08002868 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002869 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002870
2871 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002872 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873}
2874
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002875bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002876 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002877
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002878 const Region bounds(display->bounds());
2879 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002880 const auto displayId = display->getId();
2881 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002882 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002883
Chia-I Wu8e50e692018-05-04 10:12:37 -07002884 bool applyColorMatrix = false;
Peiyong Lin00f9c022018-05-09 15:35:33 -07002885 bool needsLegacyColorMatrix = false;
2886 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002887
Dan Stoza9e56aa02015-11-02 13:00:03 -08002888 if (hasClientComposition) {
2889 ALOGV("hasClientComposition");
2890
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002891 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002892 if (display->hasWideColorGamut()) {
2893 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002894 }
2895 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002896 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002897 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002898
Dominik Laskowski7e045462018-05-30 13:02:02 -07002899 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002900 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2901 HWC2::Capability::SkipClientColorTransform);
2902
2903 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2904 if (applyColorMatrix) {
Peiyong Lin00f9c022018-05-09 15:35:33 -07002905 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002906 }
2907
Chia-I Wubbb44462018-05-21 15:33:27 -07002908 needsLegacyColorMatrix =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002909 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2910 outputDataspace != Dataspace::UNKNOWN && outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002911
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002912 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002913 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002914 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002915 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002916
2917 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002918 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2919 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2920 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002921 }
2922 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002923 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002924
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002925 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002926 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002927 // when using overlays, we assume a fully transparent framebuffer
2928 // NOTE: we could reduce how much we need to clear, for instance
2929 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002930 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002931 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002932 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002933 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002934 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002935 // we're left with the letterbox region
2936 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002937 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002938
2939 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002940 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002941
Mathias Agopianb9494d52012-04-18 02:28:45 -07002942 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002943 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002944 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002945 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002946 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002947 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002948
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002949 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002950 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002951 // scissor on the main display. It should never be needed
2952 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002953 const Rect& bounds = display->getBounds();
2954 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002955 if (scissor != bounds) {
2956 // scissor doesn't match the screen's dimensions, so we
2957 // need to clear everything outside of it and enable
2958 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002959
Mathias Agopianf45c5102012-10-24 16:29:17 -07002960 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002961 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002962 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002963 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002964 }
2965 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002966 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002967
Mathias Agopian85d751c2012-08-29 16:59:24 -07002968 /*
2969 * and then, render the layers targeted at the framebuffer
2970 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002971
Dan Stoza9e56aa02015-11-02 13:00:03 -08002972 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002973 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002974 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002975 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002976 const Region clip(bounds.intersect(
2977 displayTransform.transform(layer->visibleRegion)));
2978 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002979 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002980 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002981 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002982 case HWC2::Composition::Cursor:
2983 case HWC2::Composition::Device:
2984 case HWC2::Composition::Sideband:
2985 case HWC2::Composition::SolidColor: {
2986 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002987 if (layer->getClearClientTarget(displayId) && !firstLayer &&
2988 layer->isOpaque(state) && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002989 // never clear the very first layer since we're
2990 // guaranteed the FB is already cleared
2991 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002992 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002993 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002994 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002995 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002996 // switch color matrices lazily
Peiyong Lin00f9c022018-05-09 15:35:33 -07002997 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
2998 if (!legacyColorMatrixApplied) {
2999 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
3000 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003001 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07003002 } else if (legacyColorMatrixApplied) {
3003 getRenderEngine().setSaturationMatrix(mat4());
3004 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003005 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003006
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003007 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003008 break;
3009 }
3010 default:
3011 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003012 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003013 } else {
3014 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003015 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003016 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003017 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003018
Peiyong Lin00f9c022018-05-09 15:35:33 -07003019 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003020 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003021 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07003022 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3023 getRenderEngine().setSaturationMatrix(mat4());
3024 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003025
Mathias Agopianf45c5102012-10-24 16:29:17 -07003026 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003027 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003028 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003029}
3030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003031void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3032 const Region& region) const {
3033 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003034 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003035 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003036}
3037
Dan Stoza7d89d062015-04-30 13:29:25 -07003038status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003039 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003040 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003041 const sp<Layer>& lbc,
3042 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003043{
Dan Stoza7d89d062015-04-30 13:29:25 -07003044 // add this layer to the current state list
3045 {
3046 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003047 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003048 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3049 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003050 return NO_MEMORY;
3051 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003052 if (parent == nullptr) {
3053 mCurrentState.layersSortedByZ.add(lbc);
3054 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003055 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003056 ALOGE("addClientLayer called with a removed parent");
3057 return NAME_NOT_FOUND;
3058 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003059 parent->addChild(lbc);
3060 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003061
Yiwei Zhang243b3782018-05-15 17:40:04 -07003062 if (gbc != nullptr) {
3063 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3064 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3065 mMaxGraphicBufferProducerListSize,
3066 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3067 mGraphicBufferProducerList.size(),
3068 mMaxGraphicBufferProducerListSize, mNumLayers);
3069 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003070 mLayersAdded = true;
3071 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003072 }
3073
Mathias Agopian96f08192010-06-02 23:28:45 -07003074 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003075 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003076
Dan Stoza7d89d062015-04-30 13:29:25 -07003077 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003078}
3079
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003080status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003081 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003082 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3083}
Robert Carr7f9b8992017-03-10 11:08:39 -08003084
chaviwca27f252018-02-06 16:46:39 -08003085status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3086 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003087 if (layer->isPendingRemoval()) {
3088 return NO_ERROR;
3089 }
3090
Robert Carr1f0a16a2016-10-24 16:27:39 -07003091 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003092 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003093 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003094 if (topLevelOnly) {
3095 return NO_ERROR;
3096 }
3097
Chia-I Wu98f1c102017-05-30 14:54:08 -07003098 sp<Layer> ancestor = p;
3099 while (ancestor->getParent() != nullptr) {
3100 ancestor = ancestor->getParent();
3101 }
3102 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3103 ALOGE("removeLayer called with a layer whose parent has been removed");
3104 return NAME_NOT_FOUND;
3105 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003106
3107 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003108 } else {
3109 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003110 }
3111
Robert Carr136e2f62017-02-08 17:54:29 -08003112 // As a matter of normal operation, the LayerCleaner will produce a second
3113 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3114 // so we will succeed in promoting it, but it's already been removed
3115 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3116 // otherwise something has gone wrong and we are leaking the layer.
3117 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003118 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3119 layer->getName().string(),
3120 (p != nullptr) ? p->getName().string() : "no-parent");
3121 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003122 } else if (index < 0) {
3123 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003124 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003125
Chia-I Wuc6657022017-08-15 11:18:17 -07003126 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003127 mLayersPendingRemoval.add(layer);
3128 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003129 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003130 setTransactionFlags(eTransactionNeeded);
3131 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132}
3133
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003134uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003135 return android_atomic_release_load(&mTransactionFlags);
3136}
3137
Mathias Agopian3f844832013-08-07 21:24:32 -07003138uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3140}
3141
Mathias Agopian3f844832013-08-07 21:24:32 -07003142uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003143 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3144}
3145
3146uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3147 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003149 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003150 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003151 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152 }
3153 return old;
3154}
3155
chaviwca27f252018-02-06 16:46:39 -08003156bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3157 for (const ComposerState& state : states) {
3158 // Here we need to check that the interface we're given is indeed
3159 // one of our own. A malicious client could give us a nullptr
3160 // IInterface, or one of its own or even one of our own but a
3161 // different type. All these situations would cause us to crash.
3162 if (state.client == nullptr) {
3163 return true;
3164 }
3165
3166 sp<IBinder> binder = IInterface::asBinder(state.client);
3167 if (binder == nullptr) {
3168 return true;
3169 }
3170
3171 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3172 return true;
3173 }
3174 }
3175 return false;
3176}
3177
Mathias Agopian8b33f032012-07-24 20:43:54 -07003178void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003179 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003180 const Vector<DisplayState>& displays,
3181 uint32_t flags)
3182{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003183 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003184 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003185 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003186
chaviwca27f252018-02-06 16:46:39 -08003187 if (containsAnyInvalidClientState(states)) {
3188 return;
3189 }
3190
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003191 if (flags & eAnimation) {
3192 // For window updates that are part of an animation we must wait for
3193 // previous animation "frames" to be handled.
3194 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003195 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003196 if (CC_UNLIKELY(err != NO_ERROR)) {
3197 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003198 // caller after a few seconds.
3199 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3200 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003201 mAnimTransactionPending = false;
3202 break;
3203 }
3204 }
3205 }
3206
chaviwca27f252018-02-06 16:46:39 -08003207 for (const DisplayState& display : displays) {
3208 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003209 }
3210
chaviwca27f252018-02-06 16:46:39 -08003211 for (const ComposerState& state : states) {
3212 transactionFlags |= setClientStateLocked(state);
3213 }
3214
3215 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3216 // as destroyed should only occur after setting all other states. This is to allow for a
3217 // child re-parent to happen before marking its original parent as destroyed (which would
3218 // then mark the child as destroyed).
3219 for (const ComposerState& state : states) {
3220 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003221 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003222
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003223 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3224 // anyway. This can be used as a flush mechanism for previous async transactions.
3225 // Empty animation transaction can be used to simulate back-pressure, so also force a
3226 // transaction for empty animation transactions.
3227 if (transactionFlags == 0 &&
3228 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003229 transactionFlags = eTransactionNeeded;
3230 }
3231
Mathias Agopian386aa982011-11-07 21:58:03 -08003232 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003233 if (mInterceptor->isEnabled()) {
3234 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003235 }
Irvel468051e2016-06-13 16:44:44 -07003236
Mathias Agopian386aa982011-11-07 21:58:03 -08003237 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003238 const auto start = (flags & eEarlyWakeup)
3239 ? VSyncModulator::TransactionStart::EARLY
3240 : VSyncModulator::TransactionStart::NORMAL;
3241 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003242
3243 // if this is a synchronous transaction, wait for it to take effect
3244 // before returning.
3245 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003246 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003247 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003248 if (flags & eAnimation) {
3249 mAnimTransactionPending = true;
3250 }
3251 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003252 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3253 if (CC_UNLIKELY(err != NO_ERROR)) {
3254 // just in case something goes wrong in SF, return to the
3255 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003256 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3257 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003258 break;
3259 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003260 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003261 }
3262}
3263
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003264uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3265 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3266 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003267
Mathias Agopiane57f2922012-08-09 16:29:12 -07003268 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003269 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3270
3271 const uint32_t what = s.what;
3272 if (what & DisplayState::eSurfaceChanged) {
3273 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3274 state.surface = s.surface;
3275 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003276 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003277 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003278 if (what & DisplayState::eLayerStackChanged) {
3279 if (state.layerStack != s.layerStack) {
3280 state.layerStack = s.layerStack;
3281 flags |= eDisplayTransactionNeeded;
3282 }
3283 }
3284 if (what & DisplayState::eDisplayProjectionChanged) {
3285 if (state.orientation != s.orientation) {
3286 state.orientation = s.orientation;
3287 flags |= eDisplayTransactionNeeded;
3288 }
3289 if (state.frame != s.frame) {
3290 state.frame = s.frame;
3291 flags |= eDisplayTransactionNeeded;
3292 }
3293 if (state.viewport != s.viewport) {
3294 state.viewport = s.viewport;
3295 flags |= eDisplayTransactionNeeded;
3296 }
3297 }
3298 if (what & DisplayState::eDisplaySizeChanged) {
3299 if (state.width != s.width) {
3300 state.width = s.width;
3301 flags |= eDisplayTransactionNeeded;
3302 }
3303 if (state.height != s.height) {
3304 state.height = s.height;
3305 flags |= eDisplayTransactionNeeded;
3306 }
3307 }
3308
Mathias Agopiane57f2922012-08-09 16:29:12 -07003309 return flags;
3310}
3311
Robert Carrd4ae7f32018-06-07 16:10:57 -07003312bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3313 IPCThreadState* ipc = IPCThreadState::self();
3314 const int pid = ipc->getCallingPid();
3315 const int uid = ipc->getCallingUid();
3316
3317 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3318 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3319 return false;
3320 }
3321 return true;
3322}
3323
chaviwca27f252018-02-06 16:46:39 -08003324uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3325 const layer_state_t& s = composerState.state;
3326 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3327
Mathias Agopian13127d82013-03-05 17:47:11 -08003328 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003329 if (layer == nullptr) {
3330 return 0;
3331 }
3332
3333 if (layer->isPendingRemoval()) {
3334 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3335 return 0;
3336 }
3337
3338 uint32_t flags = 0;
3339
3340 const uint32_t what = s.what;
3341 bool geometryAppliesWithResize =
3342 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003343
3344 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3345 // pending state will also be deferred.
3346 if (what & layer_state_t::eDeferTransaction) {
3347 layer->pushPendingState();
3348 }
3349
chaviw8b3871a2017-11-01 17:41:01 -07003350 if (what & layer_state_t::ePositionChanged) {
3351 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3352 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003353 }
chaviw8b3871a2017-11-01 17:41:01 -07003354 }
3355 if (what & layer_state_t::eLayerChanged) {
3356 // NOTE: index needs to be calculated before we update the state
3357 const auto& p = layer->getParent();
3358 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003359 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003360 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003361 mCurrentState.layersSortedByZ.removeAt(idx);
3362 mCurrentState.layersSortedByZ.add(layer);
3363 // we need traversal (state changed)
3364 // AND transaction (list changed)
3365 flags |= eTransactionNeeded|eTraversalNeeded;
3366 }
chaviw8b3871a2017-11-01 17:41:01 -07003367 } else {
3368 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003369 flags |= eTransactionNeeded|eTraversalNeeded;
3370 }
3371 }
chaviw8b3871a2017-11-01 17:41:01 -07003372 }
3373 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003374 // NOTE: index needs to be calculated before we update the state
3375 const auto& p = layer->getParent();
3376 if (p == nullptr) {
3377 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3378 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3379 mCurrentState.layersSortedByZ.removeAt(idx);
3380 mCurrentState.layersSortedByZ.add(layer);
3381 // we need traversal (state changed)
3382 // AND transaction (list changed)
3383 flags |= eTransactionNeeded|eTraversalNeeded;
3384 }
3385 } else {
3386 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3387 flags |= eTransactionNeeded|eTraversalNeeded;
3388 }
chaviw8b3871a2017-11-01 17:41:01 -07003389 }
3390 }
3391 if (what & layer_state_t::eSizeChanged) {
3392 if (layer->setSize(s.w, s.h)) {
3393 flags |= eTraversalNeeded;
3394 }
3395 }
3396 if (what & layer_state_t::eAlphaChanged) {
3397 if (layer->setAlpha(s.alpha))
3398 flags |= eTraversalNeeded;
3399 }
3400 if (what & layer_state_t::eColorChanged) {
3401 if (layer->setColor(s.color))
3402 flags |= eTraversalNeeded;
3403 }
3404 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003405 // TODO: b/109894387
3406 //
3407 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3408 // rotation. To see the problem observe that if we have a square parent, and a child
3409 // of the same size, then we rotate the child 45 degrees around it's center, the child
3410 // must now be cropped to a non rectangular 8 sided region.
3411 //
3412 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3413 // private API, and the WindowManager only uses rotation in one case, which is on a top
3414 // level layer in which cropping is not an issue.
3415 //
3416 // However given that abuse of rotation matrices could lead to surfaces extending outside
3417 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3418 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3419 // transformations.
3420 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003421 flags |= eTraversalNeeded;
3422 }
3423 if (what & layer_state_t::eTransparentRegionChanged) {
3424 if (layer->setTransparentRegionHint(s.transparentRegion))
3425 flags |= eTraversalNeeded;
3426 }
3427 if (what & layer_state_t::eFlagsChanged) {
3428 if (layer->setFlags(s.flags, s.mask))
3429 flags |= eTraversalNeeded;
3430 }
3431 if (what & layer_state_t::eCropChanged) {
3432 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3433 flags |= eTraversalNeeded;
3434 }
3435 if (what & layer_state_t::eFinalCropChanged) {
3436 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3437 flags |= eTraversalNeeded;
3438 }
3439 if (what & layer_state_t::eLayerStackChanged) {
3440 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3441 // We only allow setting layer stacks for top level layers,
3442 // everything else inherits layer stack from its parent.
3443 if (layer->hasParent()) {
3444 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3445 layer->getName().string());
3446 } else if (idx < 0) {
3447 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3448 "that also does not appear in the top level layer list. Something"
3449 " has gone wrong.", layer->getName().string());
3450 } else if (layer->setLayerStack(s.layerStack)) {
3451 mCurrentState.layersSortedByZ.removeAt(idx);
3452 mCurrentState.layersSortedByZ.add(layer);
3453 // we need traversal (state changed)
3454 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003455 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003456 }
3457 }
3458 if (what & layer_state_t::eDeferTransaction) {
3459 if (s.barrierHandle != nullptr) {
3460 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3461 } else if (s.barrierGbp != nullptr) {
3462 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3463 if (authenticateSurfaceTextureLocked(gbp)) {
3464 const auto& otherLayer =
3465 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3466 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3467 } else {
3468 ALOGE("Attempt to defer transaction to to an"
3469 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003470 }
3471 }
chaviw8b3871a2017-11-01 17:41:01 -07003472 // We don't trigger a traversal here because if no other state is
3473 // changed, we don't want this to cause any more work
3474 }
3475 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003476 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003477 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003478 if (!hadParent) {
3479 mCurrentState.layersSortedByZ.remove(layer);
3480 }
chaviw8b3871a2017-11-01 17:41:01 -07003481 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003482 }
chaviw8b3871a2017-11-01 17:41:01 -07003483 }
3484 if (what & layer_state_t::eReparentChildren) {
3485 if (layer->reparentChildren(s.reparentHandle)) {
3486 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003487 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003488 }
chaviw8b3871a2017-11-01 17:41:01 -07003489 if (what & layer_state_t::eDetachChildren) {
3490 layer->detachChildren();
3491 }
3492 if (what & layer_state_t::eOverrideScalingModeChanged) {
3493 layer->setOverrideScalingMode(s.overrideScalingMode);
3494 // We don't trigger a traversal here because if no other state is
3495 // changed, we don't want this to cause any more work
3496 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003497 return flags;
3498}
3499
chaviwca27f252018-02-06 16:46:39 -08003500void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3501 const layer_state_t& state = composerState.state;
3502 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3503
3504 sp<Layer> layer(client->getLayerUser(state.surface));
3505 if (layer == nullptr) {
3506 return;
3507 }
3508
3509 if (layer->isPendingRemoval()) {
3510 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3511 return;
3512 }
3513
3514 if (state.what & layer_state_t::eDestroySurface) {
3515 removeLayerLocked(mStateLock, layer);
3516 }
3517}
3518
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003519status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003520 const String8& name,
3521 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003522 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003523 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003524 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003525{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003526 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003527 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003528 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003529 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003530 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003531
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003532 status_t result = NO_ERROR;
3533
3534 sp<Layer> layer;
3535
Cody Northropbc755282017-03-31 12:00:08 -06003536 String8 uniqueName = getUniqueLayerName(name);
3537
Mathias Agopian3165cc22012-08-08 19:42:09 -07003538 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3539 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003540 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003541 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003542 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003543
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003544 break;
chaviw13fdc492017-06-27 12:40:18 -07003545 case ISurfaceComposerClient::eFXSurfaceColor:
3546 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003547 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003548 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003549 break;
3550 default:
3551 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003552 break;
3553 }
3554
Dan Stoza7d89d062015-04-30 13:29:25 -07003555 if (result != NO_ERROR) {
3556 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003557 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003558
Chia-I Wuab0c3192017-08-01 11:29:00 -07003559 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3560 // TODO b/64227542
3561 if (windowType == 441731) {
3562 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3563 layer->setPrimaryDisplayOnly();
3564 }
3565
Albert Chaulk479c60c2017-01-27 14:21:34 -05003566 layer->setInfo(windowType, ownerUid);
3567
Robert Carr1f0a16a2016-10-24 16:27:39 -07003568 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003569 if (result != NO_ERROR) {
3570 return result;
3571 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003572 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003573
3574 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003575 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576}
3577
Cody Northropbc755282017-03-31 12:00:08 -06003578String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3579{
3580 bool matchFound = true;
3581 uint32_t dupeCounter = 0;
3582
3583 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3584 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3585
Dan Stoza436ccf32018-06-21 12:10:12 -07003586 // Grab the state lock since we're accessing mCurrentState
3587 Mutex::Autolock lock(mStateLock);
3588
Cody Northropbc755282017-03-31 12:00:08 -06003589 // Loop over layers until we're sure there is no matching name
3590 while (matchFound) {
3591 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003592 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003593 if (layer->getName() == uniqueName) {
3594 matchFound = true;
3595 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3596 }
3597 });
3598 }
3599
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003600 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3601 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003602
3603 return uniqueName;
3604}
3605
David Sodman0c69cad2017-08-21 12:12:51 -07003606status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003607 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3608 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609{
3610 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003611 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003612 case PIXEL_FORMAT_TRANSPARENT:
3613 case PIXEL_FORMAT_TRANSLUCENT:
3614 format = PIXEL_FORMAT_RGBA_8888;
3615 break;
3616 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003617 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003618 break;
3619 }
3620
David Sodman0c69cad2017-08-21 12:12:51 -07003621 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3622 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003623 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003624 *handle = layer->getHandle();
3625 *gbp = layer->getProducer();
3626 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003627 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003628
David Sodman0c69cad2017-08-21 12:12:51 -07003629 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003630 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003631}
3632
chaviw13fdc492017-06-27 12:40:18 -07003633status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003634 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003635 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003636{
chaviw13fdc492017-06-27 12:40:18 -07003637 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003638 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003639 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003640}
3641
Mathias Agopianac9fa422013-02-11 16:40:36 -08003642status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003643{
Robert Carr9524cb32017-02-13 11:32:32 -08003644 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003645 status_t err = NO_ERROR;
3646 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003647 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003648 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003649 err = removeLayer(l);
3650 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3651 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003652 }
3653 return err;
3654}
3655
Mathias Agopian13127d82013-03-05 17:47:11 -08003656status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003657{
Mathias Agopian67106042013-03-14 19:18:13 -07003658 // called by ~LayerCleaner() when all references to the IBinder (handle)
3659 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003660 sp<Layer> l = layer.promote();
3661 if (l == nullptr) {
3662 // The layer has already been removed, carry on
3663 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003664 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003665 // If we have a parent, then we can continue to live as long as it does.
3666 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003667}
3668
Mathias Agopianb60314a2012-04-10 22:09:54 -07003669// ---------------------------------------------------------------------------
3670
Andy McFadden13a082e2012-08-24 10:16:42 -07003671void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003672 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3673 if (!displayToken) return;
3674
Jesse Hall01e29052013-02-19 16:13:35 -08003675 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003676 Vector<ComposerState> state;
3677 Vector<DisplayState> displays;
3678 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003679 d.what = DisplayState::eDisplayProjectionChanged |
3680 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003681 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003682 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003683 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003684 d.frame.makeInvalid();
3685 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003686 d.width = 0;
3687 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003688 displays.add(d);
3689 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003690
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003691 const auto display = getDisplayDevice(displayToken);
3692 if (!display) return;
3693
3694 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3695
3696 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003697 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003698 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003699
Brian Andersond0010582017-03-07 13:20:31 -08003700 // Use phase of 0 since phase is not known.
3701 // Use latency of 0, which will snap to the ideal latency.
3702 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003703}
3704
3705void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003706 // Async since we may be called from the main thread.
3707 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003708}
3709
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003710void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3711 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003712 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003713 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003714
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003715 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003716 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003717 return;
3718 }
3719
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003720 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003721 ALOGW("Trying to set power mode for virtual display");
3722 return;
3723 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003724
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003725 display->setPowerMode(mode);
3726
Lloyd Pique4dccc412018-01-22 17:21:36 -08003727 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003728 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003729 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003730 if (idx < 0) {
3731 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3732 return;
3733 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003734 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003735 }
3736
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003737 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003738 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003739 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003740 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003741 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003742 // FIXME: eventthread only knows about the main display right now
3743 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003744 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003745 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003746
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003747 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003748 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003749 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003750
3751 struct sched_param param = {0};
3752 param.sched_priority = 1;
3753 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3754 ALOGW("Couldn't set SCHED_FIFO on display on");
3755 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003756 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003757 // Turn off the display
3758 struct sched_param param = {0};
3759 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3760 ALOGW("Couldn't set SCHED_OTHER on display off");
3761 }
3762
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003763 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003764 disableHardwareVsync(true); // also cancels any in-progress resync
3765
Mathias Agopiancde87a32012-09-13 14:09:01 -07003766 // FIXME: eventthread only knows about the main display right now
3767 mEventThread->onScreenReleased();
3768 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003769
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003770 getHwComposer().setPowerMode(type, mode);
3771 mVisibleRegionsDirty = true;
3772 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003773 } else if (mode == HWC_POWER_MODE_DOZE ||
3774 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003775 // Update display while dozing
3776 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003777 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003778 // FIXME: eventthread only knows about the main display right now
3779 mEventThread->onScreenAcquired();
3780 resyncToHardwareVsync(true);
3781 }
3782 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3783 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003784 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003785 disableHardwareVsync(true); // also cancels any in-progress resync
3786 // FIXME: eventthread only knows about the main display right now
3787 mEventThread->onScreenReleased();
3788 }
3789 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003790 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003791 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003792 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003793 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003794
3795 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003796}
3797
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003798void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003799 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003800 const auto display = getDisplayDevice(displayToken);
3801 if (!display) {
3802 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3803 displayToken.get());
3804 } else if (display->isVirtual()) {
3805 ALOGW("Attempt to set power mode %d for virtual display", mode);
3806 } else {
3807 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003808 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003809 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003810}
3811
3812// ---------------------------------------------------------------------------
3813
Lloyd Pique755e3192018-01-31 16:46:15 -08003814status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3815 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003816 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003817
Mathias Agopianbd115332013-04-18 16:41:04 -07003818 IPCThreadState* ipc = IPCThreadState::self();
3819 const int pid = ipc->getCallingPid();
3820 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003821
Mathias Agopianbd115332013-04-18 16:41:04 -07003822 if ((uid != AID_SHELL) &&
3823 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003824 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003825 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003826 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003827 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003828 // (this would indicate SF is stuck, but we want to be able to
3829 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003830 status_t err = mStateLock.timedLock(s2ns(1));
3831 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003832 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003833 result.appendFormat(
3834 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3835 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003836 }
3837
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003838 bool dumpAll = true;
3839 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003840 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003841
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003842 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003843 if ((index < numArgs) &&
3844 (args[index] == String16("--list"))) {
3845 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003846 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003847 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003848 }
3849
3850 if ((index < numArgs) &&
3851 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003852 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003853 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003854 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003855 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003856
3857 if ((index < numArgs) &&
3858 (args[index] == String16("--latency-clear"))) {
3859 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003860 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003861 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003862 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003863
3864 if ((index < numArgs) &&
3865 (args[index] == String16("--dispsync"))) {
3866 index++;
3867 mPrimaryDispSync.dump(result);
3868 dumpAll = false;
3869 }
Dan Stozab90cf072015-03-05 11:05:59 -08003870
3871 if ((index < numArgs) &&
3872 (args[index] == String16("--static-screen"))) {
3873 index++;
3874 dumpStaticScreenStats(result);
3875 dumpAll = false;
3876 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003877
3878 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003879 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003880 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003881 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003882 dumpAll = false;
3883 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003884
3885 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3886 index++;
3887 dumpWideColorInfo(result);
3888 dumpAll = false;
3889 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003890
3891 if ((index < numArgs) &&
3892 (args[index] == String16("--enable-layer-stats"))) {
3893 index++;
3894 mLayerStats.enable();
3895 dumpAll = false;
3896 }
3897
3898 if ((index < numArgs) &&
3899 (args[index] == String16("--disable-layer-stats"))) {
3900 index++;
3901 mLayerStats.disable();
3902 dumpAll = false;
3903 }
3904
3905 if ((index < numArgs) &&
3906 (args[index] == String16("--clear-layer-stats"))) {
3907 index++;
3908 mLayerStats.clear();
3909 dumpAll = false;
3910 }
3911
3912 if ((index < numArgs) &&
3913 (args[index] == String16("--dump-layer-stats"))) {
3914 index++;
3915 mLayerStats.dump(result);
3916 dumpAll = false;
3917 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003918
3919 if ((index < numArgs) &&
3920 (args[index] == String16("--display-identification"))) {
3921 index++;
3922 dumpDisplayIdentificationData(result);
3923 dumpAll = false;
3924 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003925
3926 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3927 index++;
3928 mTimeStats.parseArgs(asProto, args, index, result);
3929 dumpAll = false;
3930 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003931 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003932
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003933 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003934 if (asProto) {
3935 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3936 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3937 } else {
3938 dumpAllLocked(args, index, result);
3939 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003940 }
3941
Mathias Agopian9795c422009-08-26 16:36:26 -07003942 if (locked) {
3943 mStateLock.unlock();
3944 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003945 }
3946 write(fd, result.string(), result.size());
3947 return NO_ERROR;
3948}
3949
Dan Stozac7014012014-02-14 15:03:43 -08003950void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3951 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003952{
Robert Carr2047fae2016-11-28 14:09:09 -08003953 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003954 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003955 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003956}
3957
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003958void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003959 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003960{
3961 String8 name;
3962 if (index < args.size()) {
3963 name = String8(args[index]);
3964 index++;
3965 }
3966
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003967 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3968 getHwComposer().isConnected(displayId)) {
3969 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3970 const nsecs_t period = activeConfig->getVsyncPeriod();
3971 result.appendFormat("%" PRId64 "\n", period);
3972 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003973
3974 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003975 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003976 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003977 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003978 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003979 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003980 }
Robert Carr2047fae2016-11-28 14:09:09 -08003981 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003982 }
3983}
3984
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003985void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003986 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003987{
3988 String8 name;
3989 if (index < args.size()) {
3990 name = String8(args[index]);
3991 index++;
3992 }
3993
Robert Carr2047fae2016-11-28 14:09:09 -08003994 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003995 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003996 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003997 }
Robert Carr2047fae2016-11-28 14:09:09 -08003998 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003999
Svetoslavd85084b2014-03-20 10:28:31 -07004000 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004001}
4002
Jamie Gennis6547ff42013-07-16 20:12:42 -07004003// This should only be called from the main thread. Otherwise it would need
4004// the lock and should use mCurrentState rather than mDrawingState.
4005void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004006 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004007 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004008 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004009
4010 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4011}
4012
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004013void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004014{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004015 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004016
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004017 if (isLayerTripleBufferingDisabled())
4018 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004019
4020 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004021 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004022 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004023 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004024 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4025 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004026 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004027}
4028
Dan Stozab90cf072015-03-05 11:05:59 -08004029void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4030{
4031 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004032 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4033 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004034 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004035 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004036 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4037 b + 1, bucketTimeSec, percent);
4038 }
David Sodman4a36e932017-11-07 14:29:47 -08004039 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004040 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004041 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004042 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004043 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004044}
4045
Dan Stozae77c7662016-05-13 11:37:28 -07004046void SurfaceFlinger::recordBufferingStats(const char* layerName,
4047 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004048 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4049 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004050 for (const auto& segment : history) {
4051 if (!segment.usedThirdBuffer) {
4052 stats.twoBufferTime += segment.totalTime;
4053 }
4054 if (segment.occupancyAverage < 1.0f) {
4055 stats.doubleBufferedTime += segment.totalTime;
4056 } else if (segment.occupancyAverage < 2.0f) {
4057 stats.tripleBufferedTime += segment.totalTime;
4058 }
4059 ++stats.numSegments;
4060 stats.totalTime += segment.totalTime;
4061 }
4062}
4063
Brian Andersond6927fb2016-07-23 23:37:30 -07004064void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4065 result.appendFormat("Layer frame timestamps:\n");
4066
4067 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4068 const size_t count = currentLayers.size();
4069 for (size_t i=0 ; i<count ; i++) {
4070 currentLayers[i]->dumpFrameEvents(result);
4071 }
4072}
4073
Dan Stozae77c7662016-05-13 11:37:28 -07004074void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4075 result.append("Buffering stats:\n");
4076 result.append(" [Layer name] <Active time> <Two buffer> "
4077 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004078 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004079 typedef std::tuple<std::string, float, float, float> BufferTuple;
4080 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004081 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004082 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004083 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004084 if (stats.numSegments == 0) {
4085 continue;
4086 }
4087 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4088 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4089 stats.totalTime;
4090 float doubleBufferRatio = static_cast<float>(
4091 stats.doubleBufferedTime) / stats.totalTime;
4092 float tripleBufferRatio = static_cast<float>(
4093 stats.tripleBufferedTime) / stats.totalTime;
4094 sorted.insert({activeTime, {name, twoBufferRatio,
4095 doubleBufferRatio, tripleBufferRatio}});
4096 }
4097 for (const auto& sortedPair : sorted) {
4098 float activeTime = sortedPair.first;
4099 const BufferTuple& values = sortedPair.second;
4100 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4101 std::get<0>(values).c_str(), activeTime,
4102 std::get<1>(values), std::get<2>(values),
4103 std::get<3>(values));
4104 }
4105 result.append("\n");
4106}
4107
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004108void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004109 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004110 const int32_t displayId = display->getId();
4111 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4112 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004113 continue;
4114 }
4115
Dominik Laskowski7e045462018-05-30 13:02:02 -07004116 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004117 uint8_t port;
4118 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004119 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004120 result.append("no identification data\n");
4121 continue;
4122 }
4123
4124 if (!isEdid(data)) {
4125 result.append("unknown identification data: ");
4126 for (uint8_t byte : data) {
4127 result.appendFormat("%x ", byte);
4128 }
4129 result.append("\n");
4130 continue;
4131 }
4132
4133 const auto edid = parseEdid(data);
4134 if (!edid) {
4135 result.append("invalid EDID: ");
4136 for (uint8_t byte : data) {
4137 result.appendFormat("%x ", byte);
4138 }
4139 result.append("\n");
4140 continue;
4141 }
4142
4143 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4144 result.append(edid->displayName.data(), edid->displayName.length());
4145 result.append("\"\n");
4146 }
4147 result.append("\n");
4148}
4149
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004150void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4151 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004152 result.appendFormat("DisplayColorSetting: %s\n",
4153 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004154
4155 // TODO: print out if wide-color mode is active or not
4156
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004157 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004158 const int32_t displayId = display->getId();
4159 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004160 continue;
4161 }
4162
Dominik Laskowski7e045462018-05-30 13:02:02 -07004163 result.appendFormat("Display %d color modes:\n", displayId);
4164 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004165 for (auto&& mode : modes) {
4166 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4167 }
4168
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004169 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004170 result.appendFormat(" Current color mode: %s (%d)\n",
4171 decodeColorMode(currentMode).c_str(), currentMode);
4172 }
4173 result.append("\n");
4174}
4175
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004176LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004177 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004178 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4179 const State& state = useDrawing ? mDrawingState : mCurrentState;
4180 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004181 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004182 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004183 });
4184
4185 return layersProto;
4186}
4187
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004188LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004189 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004190
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004191 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004192 resolution->set_w(display.getWidth());
4193 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004194
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004195 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4196 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4197 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004198
Dominik Laskowski7e045462018-05-30 13:02:02 -07004199 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004200 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004201 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004202 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004203 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004204 }
4205 });
4206
4207 return layersProto;
4208}
4209
Mathias Agopian74d211a2013-04-22 16:55:35 +02004210void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4211 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004212{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004213 bool colorize = false;
4214 if (index < args.size()
4215 && (args[index] == String16("--color"))) {
4216 colorize = true;
4217 index++;
4218 }
4219
4220 Colorizer colorizer(colorize);
4221
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004222 // figure out if we're stuck somewhere
4223 const nsecs_t now = systemTime();
4224 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4225 const nsecs_t inTransaction(mDebugInTransaction);
4226 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4227 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4228
4229 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004230 * Dump library configuration.
4231 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004232
4233 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004234 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004235 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004236 appendSfConfigString(result);
4237 appendUiConfigString(result);
4238 appendGuiConfigString(result);
4239 result.append("\n");
4240
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004241 result.append("\nDisplay identification data:\n");
4242 dumpDisplayIdentificationData(result);
4243
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004244 result.append("\nWide-Color information:\n");
4245 dumpWideColorInfo(result);
4246
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004247 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004248 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004249 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004250 result.append(SyncFeatures::getInstance().toString());
4251 result.append("\n");
4252
Andy McFadden41d67d72014-04-25 16:58:34 -07004253 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004254 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004255 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004256
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004257 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4258 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004259 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4260 getHwComposer().isConnected(displayId)) {
4261 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004262 result.appendFormat("Display %d: "
4263 "app phase %" PRId64 " ns, "
4264 "sf phase %" PRId64 " ns, "
4265 "early app phase %" PRId64 " ns, "
4266 "early sf phase %" PRId64 " ns, "
4267 "early app gl phase %" PRId64 " ns, "
4268 "early sf gl phase %" PRId64 " ns, "
4269 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4270 displayId,
4271 vsyncPhaseOffsetNs,
4272 sfVsyncPhaseOffsetNs,
4273 appEarlyOffset,
4274 sfEarlyOffset,
4275 appEarlyGlOffset,
4276 sfEarlyOffset,
4277 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004278 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004279 result.append("\n");
4280
Dan Stozab90cf072015-03-05 11:05:59 -08004281 // Dump static screen stats
4282 result.append("\n");
4283 dumpStaticScreenStats(result);
4284 result.append("\n");
4285
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004286 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4287
Dan Stozae77c7662016-05-13 11:37:28 -07004288 dumpBufferingStats(result);
4289
Andy McFadden4803b742012-09-24 19:07:20 -07004290 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004291 * Dump the visible layer list
4292 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004293 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004294 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004295 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4296 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004297 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004298
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004299 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004300 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004301 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004302 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004303
4304 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004305 * Dump Display state
4306 */
4307
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004308 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004309 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004310 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004311 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004312 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004313 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004314 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004315
4316 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004317 * Dump SurfaceFlinger global state
4318 */
4319
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004320 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004321 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004322 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004323
Mathias Agopian888c8222012-08-04 21:10:38 -07004324 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004325 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004326
David Sodmanbc815282017-11-05 18:57:52 -08004327 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004328
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004329 if (display) {
4330 display->undefinedRegion.dump(result, "undefinedRegion");
4331 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4332 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004333 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004334 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4335 " last transaction time : %f us\n"
4336 " transaction-flags : %08x\n"
4337 " gpu_to_cpu_unsupported : %d\n",
4338 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4339 mTransactionFlags, !mGpuToCpuSupported);
4340
4341 if (display) {
4342 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4343 result.appendFormat(" refresh-rate : %f fps\n"
4344 " x-dpi : %f\n"
4345 " y-dpi : %f\n",
4346 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4347 activeConfig->getDpiY());
4348 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004349
Mathias Agopian74d211a2013-04-22 16:55:35 +02004350 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004351 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004352
Mathias Agopian74d211a2013-04-22 16:55:35 +02004353 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004354 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004355
4356 /*
4357 * VSYNC state
4358 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004359 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004360 result.append("\n");
4361
4362 /*
4363 * HWC layer minidump
4364 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004365 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004366 const int32_t displayId = display->getId();
4367 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004368 continue;
4369 }
4370
Dominik Laskowski7e045462018-05-30 13:02:02 -07004371 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004372 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004373 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004374 result.append("\n");
4375 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004376
4377 /*
4378 * Dump HWComposer state
4379 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004380 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004381 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004382 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004383 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004384 result.appendFormat(" h/w composer %s\n",
4385 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004386 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004387
4388 /*
4389 * Dump gralloc state
4390 */
4391 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4392 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004393
4394 /*
4395 * Dump VrFlinger state if in use.
4396 */
4397 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4398 result.append("VrFlinger state:\n");
4399 result.append(mVrFlinger->Dump().c_str());
4400 result.append("\n");
4401 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004402}
4403
Dominik Laskowski7e045462018-05-30 13:02:02 -07004404const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004405 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004406 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004407 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004408 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004409 }
4410 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004411
4412 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4413 static const Vector<sp<Layer>> empty;
4414 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004415}
4416
Keun young Park63f165f2012-08-31 10:53:36 -07004417bool SurfaceFlinger::startDdmConnection()
4418{
4419 void* libddmconnection_dso =
4420 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4421 if (!libddmconnection_dso) {
4422 return false;
4423 }
4424 void (*DdmConnection_start)(const char* name);
4425 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004426 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004427 if (!DdmConnection_start) {
4428 dlclose(libddmconnection_dso);
4429 return false;
4430 }
4431 (*DdmConnection_start)(getServiceName());
4432 return true;
4433}
4434
Chia-I Wu28f320b2018-05-03 11:02:56 -07004435void SurfaceFlinger::updateColorMatrixLocked() {
4436 mat4 colorMatrix;
4437 if (mGlobalSaturationFactor != 1.0f) {
4438 // Rec.709 luma coefficients
4439 float3 luminance{0.213f, 0.715f, 0.072f};
4440 luminance *= 1.0f - mGlobalSaturationFactor;
4441 mat4 saturationMatrix = mat4(
4442 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4443 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4444 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4445 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4446 );
4447 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4448 } else {
4449 colorMatrix = mClientColorMatrix * mDaltonizer();
4450 }
4451
4452 if (mCurrentState.colorMatrix != colorMatrix) {
4453 mCurrentState.colorMatrix = colorMatrix;
4454 mCurrentState.colorMatrixChanged = true;
4455 setTransactionFlags(eTransactionNeeded);
4456 }
4457}
4458
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004459status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004460 switch (code) {
4461 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004462 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004463 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004464 case CLEAR_ANIMATION_FRAME_STATS:
4465 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004466 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004467 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004468 case ENABLE_VSYNC_INJECTIONS:
4469 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004470 {
4471 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004472 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4473 IPCThreadState* ipc = IPCThreadState::self();
4474 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4475 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004476 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004477 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004478 break;
4479 }
Robert Carr1db73f62016-12-21 12:58:51 -08004480 /*
4481 * Calling setTransactionState is safe, because you need to have been
4482 * granted a reference to Client* and Handle* to do anything with it.
4483 *
4484 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4485 */
4486 case SET_TRANSACTION_STATE:
4487 case CREATE_SCOPED_CONNECTION:
4488 {
4489 return OK;
4490 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004491 case CAPTURE_SCREEN:
4492 {
4493 // codes that require permission check
4494 IPCThreadState* ipc = IPCThreadState::self();
4495 const int pid = ipc->getCallingPid();
4496 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004497 if ((uid != AID_GRAPHICS) &&
4498 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004499 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004500 return PERMISSION_DENIED;
4501 }
4502 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004503 }
chaviwa76b2712017-09-20 12:02:26 -07004504 case CAPTURE_LAYERS: {
4505 IPCThreadState* ipc = IPCThreadState::self();
4506 const int pid = ipc->getCallingPid();
4507 const int uid = ipc->getCallingUid();
4508 if ((uid != AID_GRAPHICS) &&
4509 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4510 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4511 return PERMISSION_DENIED;
4512 }
4513 break;
4514 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004515 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004516 return OK;
4517}
4518
4519status_t SurfaceFlinger::onTransact(
4520 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4521{
4522 status_t credentialCheck = CheckTransactCodeCredentials(code);
4523 if (credentialCheck != OK) {
4524 return credentialCheck;
4525 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004526
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004527 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4528 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004529 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004530 IPCThreadState* ipc = IPCThreadState::self();
4531 const int uid = ipc->getCallingUid();
4532 if (CC_UNLIKELY(uid != AID_SYSTEM
4533 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004534 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004535 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004536 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004537 return PERMISSION_DENIED;
4538 }
4539 int n;
4540 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004541 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004542 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004543 return NO_ERROR;
4544 case 1002: // SHOW_UPDATES
4545 n = data.readInt32();
4546 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004547 invalidateHwcGeometry();
4548 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004549 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004550 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004551 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004552 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004553 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004554 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004555 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004556 setTransactionFlags(
4557 eTransactionNeeded|
4558 eDisplayTransactionNeeded|
4559 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004560 return NO_ERROR;
4561 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004562 case 1006:{ // send empty update
4563 signalRefresh();
4564 return NO_ERROR;
4565 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004566 case 1008: // toggle use of hw composer
4567 n = data.readInt32();
4568 mDebugDisableHWC = n ? 1 : 0;
4569 invalidateHwcGeometry();
4570 repaintEverything();
4571 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004572 case 1009: // toggle use of transform hint
4573 n = data.readInt32();
4574 mDebugDisableTransformHint = n ? 1 : 0;
4575 invalidateHwcGeometry();
4576 repaintEverything();
4577 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004578 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004579 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004580 reply->writeInt32(0);
4581 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004582 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004583 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004584 return NO_ERROR;
4585 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004586 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004587 if (!display) {
4588 return NAME_NOT_FOUND;
4589 }
4590
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004591 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004592 return NO_ERROR;
4593 }
4594 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004595 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004596 // daltonize
4597 n = data.readInt32();
4598 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004599 case 1:
4600 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4601 break;
4602 case 2:
4603 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4604 break;
4605 case 3:
4606 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4607 break;
4608 default:
4609 mDaltonizer.setType(ColorBlindnessType::None);
4610 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004611 }
4612 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004613 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004614 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004615 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004616 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004617
4618 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004619 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004620 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004621 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004622 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004623 // apply a color matrix
4624 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004625 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004626 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004627 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004628 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004629 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004630 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004631 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004632 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004633 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004634 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004635
4636 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4637 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004638 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004639 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4640 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4641 }
4642
Chia-I Wu28f320b2018-05-03 11:02:56 -07004643 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004644 return NO_ERROR;
4645 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004646 // This is an experimental interface
4647 // Needs to be shifted to proper binder interface when we productize
4648 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004649 n = data.readInt32();
4650 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004651 return NO_ERROR;
4652 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004653 case 1017: {
4654 n = data.readInt32();
4655 mForceFullDamage = static_cast<bool>(n);
4656 return NO_ERROR;
4657 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004658 case 1018: { // Modify Choreographer's phase offset
4659 n = data.readInt32();
4660 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4661 return NO_ERROR;
4662 }
4663 case 1019: { // Modify SurfaceFlinger's phase offset
4664 n = data.readInt32();
4665 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4666 return NO_ERROR;
4667 }
Irvel468051e2016-06-13 16:44:44 -07004668 case 1020: { // Layer updates interceptor
4669 n = data.readInt32();
4670 if (n) {
4671 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004672 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004673 }
4674 else{
4675 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004676 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004677 }
4678 return NO_ERROR;
4679 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004680 case 1021: { // Disable HWC virtual displays
4681 n = data.readInt32();
4682 mUseHwcVirtualDisplays = !n;
4683 return NO_ERROR;
4684 }
Romain Guy0147a172017-06-01 13:53:56 -07004685 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004686 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004687 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004688
Chia-I Wu28f320b2018-05-03 11:02:56 -07004689 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004690 return NO_ERROR;
4691 }
Romain Guy54f154a2017-10-24 21:40:32 +01004692 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004693 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004694 invalidateHwcGeometry();
4695 repaintEverything();
4696 return NO_ERROR;
4697 }
4698 case 1024: { // Is wide color gamut rendering/color management supported?
4699 reply->writeBool(hasWideColorDisplay);
4700 return NO_ERROR;
4701 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004702 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004703 n = data.readInt32();
4704 if (n) {
4705 ALOGV("LayerTracing enabled");
4706 mTracing.enable();
4707 doTracing("tracing.enable");
4708 reply->writeInt32(NO_ERROR);
4709 } else {
4710 ALOGV("LayerTracing disabled");
4711 status_t err = mTracing.disable();
4712 reply->writeInt32(err);
4713 }
4714 return NO_ERROR;
4715 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004716 case 1026: { // Get layer tracing status
4717 reply->writeBool(mTracing.isEnabled());
4718 return NO_ERROR;
4719 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004720 // Is a DisplayColorSetting supported?
4721 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004722 const auto display = getDefaultDisplayDevice();
4723 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004724 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004725 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004726
4727 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4728 switch (setting) {
4729 case DisplayColorSetting::MANAGED:
4730 reply->writeBool(hasWideColorDisplay);
4731 break;
4732 case DisplayColorSetting::UNMANAGED:
4733 reply->writeBool(true);
4734 break;
4735 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004736 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004737 break;
4738 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004739 reply->writeBool(
4740 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004741 break;
4742 }
4743 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004744 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004745 // Is VrFlinger active?
4746 case 1028: {
4747 Mutex::Autolock _l(mStateLock);
4748 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4749 return NO_ERROR;
4750 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004751 }
4752 }
4753 return err;
4754}
4755
Steven Thomas6d8110b2017-08-31 18:24:21 -07004756void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004757 android_atomic_or(1, &mRepaintEverything);
4758 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004759}
4760
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004761// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4762class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004763public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004764 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4765 ~WindowDisconnector() {
4766 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004767 }
4768
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004769private:
4770 ANativeWindow* mWindow;
4771 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004772};
4773
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004774status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4775 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4776 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4777 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004778 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004779 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004780
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004781 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004782
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004783 const auto display = getDisplayDeviceLocked(displayToken);
4784 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004785
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004786 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004787
4788 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004789 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004790 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004791}
4792
4793status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004794 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004795 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004796 ATRACE_CALL();
4797
4798 class LayerRenderArea : public RenderArea {
4799 public:
Robert Carr578038f2018-03-09 12:25:24 -08004800 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4801 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004802 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004803 mLayer(layer),
4804 mCrop(crop),
4805 mFlinger(flinger),
4806 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004807 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004808 Rect getBounds() const override {
4809 const Layer::State& layerState(mLayer->getDrawingState());
4810 return Rect(layerState.active.w, layerState.active.h);
4811 }
4812 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4813 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4814 bool isSecure() const override { return false; }
4815 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004816 Rect getSourceCrop() const override {
4817 if (mCrop.isEmpty()) {
4818 return getBounds();
4819 } else {
4820 return mCrop;
4821 }
4822 }
Robert Carr578038f2018-03-09 12:25:24 -08004823 class ReparentForDrawing {
4824 public:
4825 const sp<Layer>& oldParent;
4826 const sp<Layer>& newParent;
4827
4828 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4829 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004830 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004831 }
Robert Carr15eae092018-03-23 13:43:53 -07004832 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004833 };
4834
4835 void render(std::function<void()> drawLayers) override {
4836 if (!mChildrenOnly) {
4837 mTransform = mLayer->getTransform().inverse();
4838 drawLayers();
4839 } else {
4840 Rect bounds = getBounds();
4841 screenshotParentLayer =
4842 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4843 bounds.getWidth(), bounds.getHeight(), 0);
4844
4845 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4846 drawLayers();
4847 }
4848 }
chaviwa76b2712017-09-20 12:02:26 -07004849
chaviwa76b2712017-09-20 12:02:26 -07004850 private:
chaviw7206d492017-11-10 16:16:12 -08004851 const sp<Layer> mLayer;
4852 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004853
4854 // In the "childrenOnly" case we reparent the children to a screenshot
4855 // layer which has no properties set and which does not draw.
4856 sp<ContainerLayer> screenshotParentLayer;
4857 Transform mTransform;
4858
4859 SurfaceFlinger* mFlinger;
4860 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004861 };
4862
4863 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4864 auto parent = layerHandle->owner.promote();
4865
chaviw7206d492017-11-10 16:16:12 -08004866 if (parent == nullptr || parent->isPendingRemoval()) {
4867 ALOGE("captureLayers called with a removed parent");
4868 return NAME_NOT_FOUND;
4869 }
4870
Robert Carr578038f2018-03-09 12:25:24 -08004871 const int uid = IPCThreadState::self()->getCallingUid();
4872 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4873 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4874 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4875 return PERMISSION_DENIED;
4876 }
4877
chaviw7206d492017-11-10 16:16:12 -08004878 Rect crop(sourceCrop);
4879 if (sourceCrop.width() <= 0) {
4880 crop.left = 0;
4881 crop.right = parent->getCurrentState().active.w;
4882 }
4883
4884 if (sourceCrop.height() <= 0) {
4885 crop.top = 0;
4886 crop.bottom = parent->getCurrentState().active.h;
4887 }
4888
4889 int32_t reqWidth = crop.width() * frameScale;
4890 int32_t reqHeight = crop.height() * frameScale;
4891
Robert Carr578038f2018-03-09 12:25:24 -08004892 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004893
Robert Carr578038f2018-03-09 12:25:24 -08004894 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004895 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4896 if (!layer->isVisible()) {
4897 return;
Robert Carr578038f2018-03-09 12:25:24 -08004898 } else if (childrenOnly && layer == parent.get()) {
4899 return;
chaviwa76b2712017-09-20 12:02:26 -07004900 }
4901 visitor(layer);
4902 });
4903 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004904 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004905}
4906
4907status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4908 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004909 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004910 bool useIdentityTransform) {
4911 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004912
Iris Chang7501ed62018-04-30 14:45:42 +08004913 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004914
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004915 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4916 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4917 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4918 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004919
4920 // This mutex protects syncFd and captureResult for communication of the return values from the
4921 // main thread back to this Binder thread
4922 std::mutex captureMutex;
4923 std::condition_variable captureCondition;
4924 std::unique_lock<std::mutex> captureLock(captureMutex);
4925 int syncFd = -1;
4926 std::optional<status_t> captureResult;
4927
Robert Carr03480e22018-01-04 16:02:06 -08004928 const int uid = IPCThreadState::self()->getCallingUid();
4929 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4930
Dominik Laskowski8c001672018-05-30 16:52:06 -07004931 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004932 // If there is a refresh pending, bug out early and tell the binder thread to try again
4933 // after the refresh.
4934 if (mRefreshPending) {
4935 ATRACE_NAME("Skipping screenshot for now");
4936 std::unique_lock<std::mutex> captureLock(captureMutex);
4937 captureResult = std::make_optional<status_t>(EAGAIN);
4938 captureCondition.notify_one();
4939 return;
4940 }
4941
4942 status_t result = NO_ERROR;
4943 int fd = -1;
4944 {
4945 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07004946 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08004947 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4948 useIdentityTransform, forSystem, &fd);
4949 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004950 }
4951
4952 {
4953 std::unique_lock<std::mutex> captureLock(captureMutex);
4954 syncFd = fd;
4955 captureResult = std::make_optional<status_t>(result);
4956 captureCondition.notify_one();
4957 }
4958 });
4959
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004960 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004961 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004962 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004963 while (*captureResult == EAGAIN) {
4964 captureResult.reset();
4965 result = postMessageAsync(message);
4966 if (result != NO_ERROR) {
4967 return result;
4968 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07004969 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004970 }
4971 result = *captureResult;
4972 }
4973
4974 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004975 sync_wait(syncFd, -1);
4976 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004977 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004978
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004979 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004980}
4981
chaviwa76b2712017-09-20 12:02:26 -07004982void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4983 TraverseLayersFunction traverseLayers, bool yswap,
4984 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004985 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004986
Lloyd Pique144e1162017-12-20 16:44:52 -08004987 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004988
4989 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004990 const auto raWidth = renderArea.getWidth();
4991 const auto raHeight = renderArea.getHeight();
4992
4993 const auto reqWidth = renderArea.getReqWidth();
4994 const auto reqHeight = renderArea.getReqHeight();
4995 Rect sourceCrop = renderArea.getSourceCrop();
4996
Iris Chang7501ed62018-04-30 14:45:42 +08004997 bool filtering = false;
4998 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4999 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5000 static_cast<int32_t>(reqHeight) != raWidth;
5001 } else {
5002 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5003 static_cast<int32_t>(reqHeight) != raHeight;
5004 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005005
Dan Stozac1879002014-05-22 15:59:05 -07005006 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005007 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005008 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005009 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005010 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5011 Transform tr;
5012 uint32_t flags = 0x00;
5013 switch (mPrimaryDisplayOrientation) {
5014 case DisplayState::eOrientation90:
5015 flags = Transform::ROT_90;
5016 break;
5017 case DisplayState::eOrientation180:
5018 flags = Transform::ROT_180;
5019 break;
5020 case DisplayState::eOrientation270:
5021 flags = Transform::ROT_270;
5022 break;
5023 }
5024 tr.set(flags, raWidth, raHeight);
5025 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005026 }
5027
5028 // ensure that sourceCrop is inside screen
5029 if (sourceCrop.left < 0) {
5030 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5031 }
chaviwa76b2712017-09-20 12:02:26 -07005032 if (sourceCrop.right > raWidth) {
5033 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005034 }
5035 if (sourceCrop.top < 0) {
5036 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5037 }
chaviwa76b2712017-09-20 12:02:26 -07005038 if (sourceCrop.bottom > raHeight) {
5039 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005040 }
5041
Chia-I Wu36574d92018-05-16 10:54:36 -07005042 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5043 engine.setOutputDataSpace(Dataspace::SRGB);
5044 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005045
Mathias Agopian180f10d2013-04-10 22:55:41 -07005046 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005047 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005048
Iris Chang7501ed62018-04-30 14:45:42 +08005049 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5050 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5051 // convert hw orientation into flag presentation
5052 // here inverse transform needed
5053 uint8_t hw_rot_90 = 0x00;
5054 uint8_t hw_flip_hv = 0x00;
5055 switch (mPrimaryDisplayOrientation) {
5056 case DisplayState::eOrientation90:
5057 hw_rot_90 = Transform::ROT_90;
5058 hw_flip_hv = Transform::ROT_180;
5059 break;
5060 case DisplayState::eOrientation180:
5061 hw_flip_hv = Transform::ROT_180;
5062 break;
5063 case DisplayState::eOrientation270:
5064 hw_rot_90 = Transform::ROT_90;
5065 break;
5066 }
5067
5068 // transform flags operation
5069 // 1) flip H V if both have ROT_90 flag
5070 // 2) XOR these flags
5071 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5072 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5073 if (rotation_rot_90 & hw_rot_90) {
5074 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5075 }
5076 rotation = static_cast<Transform::orientation_flags>
5077 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5078 }
5079
Mathias Agopian180f10d2013-04-10 22:55:41 -07005080 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005081 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005082 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005083 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005084
chaviw50da5042018-04-09 13:49:37 -07005085 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005086 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005087 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005088
chaviwa76b2712017-09-20 12:02:26 -07005089 traverseLayers([&](Layer* layer) {
5090 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07005091 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005092 if (filtering) layer->setFiltering(false);
5093 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005094}
5095
chaviwa76b2712017-09-20 12:02:26 -07005096status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5097 TraverseLayersFunction traverseLayers,
5098 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005099 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005100 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005101 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005102 ATRACE_CALL();
5103
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005104 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005105
5106 traverseLayers([&](Layer* layer) {
5107 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5108 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005109
Robert Carr03480e22018-01-04 16:02:06 -08005110 // We allow the system server to take screenshots of secure layers for
5111 // use in situations like the Screen-rotation animation and place
5112 // the impetus on WindowManager to not persist them.
5113 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005114 ALOGW("FB is protected: PERMISSION_DENIED");
5115 return PERMISSION_DENIED;
5116 }
5117
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005118 // this binds the given EGLImage as a framebuffer for the
5119 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005120 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005121 if (bufferBond.getStatus() != NO_ERROR) {
5122 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005123 return INVALID_OPERATION;
5124 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005125
Dan Stozaabcda352017-06-01 14:37:39 -07005126 // this will in fact render into our dequeued buffer
5127 // via an FBO, which means we didn't have to create
5128 // an EGLSurface and therefore we're not
5129 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005130 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005131
Dan Stozaabcda352017-06-01 14:37:39 -07005132 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005133 getRenderEngine().finish();
5134 *outSyncFd = -1;
5135
chaviwa76b2712017-09-20 12:02:26 -07005136 const auto reqWidth = renderArea.getReqWidth();
5137 const auto reqHeight = renderArea.getReqHeight();
5138
Dan Stozaabcda352017-06-01 14:37:39 -07005139 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5140 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005141 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005142 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005143 } else {
5144 base::unique_fd syncFd = getRenderEngine().flush();
5145 if (syncFd < 0) {
5146 getRenderEngine().finish();
5147 }
5148 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005149 }
5150
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005151 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005152}
5153
Mathias Agopiand5556842013-09-19 17:08:37 -07005154void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005155 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005156 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005157 for (size_t y = 0; y < h; y++) {
5158 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5159 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005160 if (p[x] != 0xFF000000) return;
5161 }
5162 }
chaviwa76b2712017-09-20 12:02:26 -07005163 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005164
Robert Carr2047fae2016-11-28 14:09:09 -08005165 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005166 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005167 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005168 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5169 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5170 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5171 static_cast<float>(state.color.a));
5172 i++;
5173 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005174 }
5175}
5176
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005177// ---------------------------------------------------------------------------
5178
Dan Stoza412903f2017-04-27 13:42:17 -07005179void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5180 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005181}
5182
Dan Stoza412903f2017-04-27 13:42:17 -07005183void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5184 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005185}
5186
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005187void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5188 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005189 const LayerVector::Visitor& visitor) {
5190 // We loop through the first level of layers without traversing,
5191 // as we need to interpret min/max layer Z in the top level Z space.
5192 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005193 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005194 continue;
5195 }
5196 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005197 // relative layers are traversed in Layer::traverseInZOrder
5198 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005199 continue;
5200 }
5201 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005202 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005203 return;
5204 }
chaviwa76b2712017-09-20 12:02:26 -07005205 if (!layer->isVisible()) {
5206 return;
5207 }
5208 visitor(layer);
5209 });
5210 }
5211}
5212
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005213}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005214
Chia-I Wu30505fb2018-03-26 16:20:31 -07005215
Mathias Agopian3f844832013-08-07 21:24:32 -07005216#if defined(__gl_h_)
5217#error "don't include gl/gl.h in this file"
5218#endif
5219
5220#if defined(__gl2_h_)
5221#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005222#endif