blob: e39e62343f2bcbb72b2fde0f08c97f15e062e07d [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include "Effects/Daltonizer.h"
87
Mathias Agopian875d8e12013-06-07 15:35:48 -070088#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070089#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070090
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080092#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
93#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090094#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090095
chaviw1d044282017-09-27 12:19:28 -070096#include <layerproto/LayerProtoParser.h>
97
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080098#define DISPLAY_COUNT 1
99
Mathias Agopianfee2b462013-07-03 12:34:01 -0700100/*
101 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
102 * black pixels.
103 */
104#define DEBUG_SCREENSHOTS false
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107
Jaesoo Lee43518572017-01-23 19:03:16 +0900108using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700110using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700111using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700112using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700113using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
Steven Thomasb02664d2017-07-26 18:48:28 -0700115namespace {
116class ConditionalLock {
117public:
118 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
119 if (lock) {
120 mMutex.lock();
121 }
122 }
123 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
124private:
125 Mutex& mMutex;
126 bool mLocked;
127};
128} // namespace anonymous
129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130// ---------------------------------------------------------------------------
131
Mathias Agopian99b49842011-06-27 16:05:52 -0700132const String16 sHardwareTest("android.permission.HARDWARE_TEST");
133const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
134const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
135const String16 sDump("android.permission.DUMP");
136
137// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800138int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
139int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700140int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700141bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800142uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800143bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800144bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800145int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800146// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600147bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700148
Kalle Raitaa099a242017-01-11 11:17:29 -0800149
150std::string getHwcServiceName() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.hwc_service_name", value, "default");
153 ALOGI("Using HWComposer service: '%s'", value);
154 return std::string(value);
155}
156
157bool useTrebleTestingOverride() {
158 char value[PROPERTY_VALUE_MAX] = {};
159 property_get("debug.sf.treble_testing_override", value, "false");
160 ALOGI("Treble testing override: '%s'", value);
161 return std::string(value) == "true";
162}
163
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800164std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
165 switch(displayColorSetting) {
166 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700167 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800168 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700169 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800170 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700171 return std::string("Enhanced");
172 default:
173 return std::string("Unknown ") +
174 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800175 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800176}
177
Lloyd Pique99d3da52018-01-22 17:48:03 -0800178NativeWindowSurface::~NativeWindowSurface() = default;
179
180namespace impl {
181
182class NativeWindowSurface final : public android::NativeWindowSurface {
183public:
184 static std::unique_ptr<android::NativeWindowSurface> create(
185 const sp<IGraphicBufferProducer>& producer) {
186 return std::make_unique<NativeWindowSurface>(producer);
187 }
188
189 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
190 : surface(new Surface(producer, false)) {}
191
192 ~NativeWindowSurface() override = default;
193
194private:
195 sp<ANativeWindow> getNativeWindow() const override { return surface; }
196
197 void preallocateBuffers() override { surface->allocateBuffers(); }
198
199 sp<Surface> surface;
200};
201
202} // namespace impl
203
David Sodmanbc815282017-11-05 18:57:52 -0800204SurfaceFlingerBE::SurfaceFlingerBE()
205 : mHwcServiceName(getHwcServiceName()),
206 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800207 mFrameBuckets(),
208 mTotalTime(0),
209 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800210 mComposerSequenceId(0) {
211}
212
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800213SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800214 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800215 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700216 mTransactionPending(false),
217 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700218 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700219 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700220 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800221 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700222 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800224 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800225 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700227 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700228 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700229 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700230 mDebugInSwapBuffers(0),
231 mLastSwapBufferTime(0),
232 mDebugInTransaction(0),
233 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700234 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700235 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000236 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700237 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700238 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800239 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800240 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700241 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800242 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800243 mCreateBufferQueue(&BufferQueue::createBufferQueue),
244 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800245
246SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800247 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800248
249 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
250 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
251
252 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
253 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
254
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800255 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
256 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700258 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
259 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
260
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700261 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
262 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
263
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800264 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
265 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
266
Steven Thomas050b2c82017-03-06 11:45:16 -0800267 // Vr flinger is only enabled on Daydream ready devices.
268 useVrFlinger = getBool< ISurfaceFlingerConfigs,
269 &ISurfaceFlingerConfigs::useVrFlinger>(false);
270
Fabien Sanglard1971b632017-03-10 14:50:03 -0800271 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
272 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
273
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600274 hasWideColorDisplay =
275 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
276
Iris Chang7501ed62018-04-30 14:45:42 +0800277 V1_1::DisplayOrientation primaryDisplayOrientation =
278 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
279 V1_1::DisplayOrientation::ORIENTATION_0);
280
281 switch (primaryDisplayOrientation) {
282 case V1_1::DisplayOrientation::ORIENTATION_90:
283 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
284 break;
285 case V1_1::DisplayOrientation::ORIENTATION_180:
286 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
287 break;
288 case V1_1::DisplayOrientation::ORIENTATION_270:
289 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
290 break;
291 default:
292 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
293 break;
294 }
295 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
296
David Sodman99974d22017-11-28 12:04:33 -0800297 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700298
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299 // debugging stuff...
300 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700301
Mathias Agopianb4b17302013-03-20 18:36:41 -0700302 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700303 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700304
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 property_get("debug.sf.showupdates", value, "0");
306 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700307
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700308 property_get("debug.sf.ddms", value, "0");
309 mDebugDDMS = atoi(value);
310 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700311 if (!startDdmConnection()) {
312 // start failed, and DDMS debugging not enabled
313 mDebugDDMS = 0;
314 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700315 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700316 ALOGI_IF(mDebugRegion, "showupdates enabled");
317 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700318
319 property_get("debug.sf.disable_backpressure", value, "0");
320 mPropagateBackpressure = !atoi(value);
321 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700322
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800323 property_get("debug.sf.enable_hwc_vds", value, "0");
324 mUseHwcVirtualDisplays = atoi(value);
325 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800326
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800327 property_get("ro.sf.disable_triple_buffer", value, "1");
328 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800329 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700330
Yiwei Zhang243b3782018-05-15 17:40:04 -0700331 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700332 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
333 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
334
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200335 property_get("debug.sf.early_phase_offset_ns", value, "-1");
336 const int earlySfOffsetNs = atoi(value);
337
338 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
339 const int earlyGlSfOffsetNs = atoi(value);
340
341 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
342 const int earlyAppOffsetNs = atoi(value);
343
344 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
345 const int earlyGlAppOffsetNs = atoi(value);
346
347 const VSyncModulator::Offsets earlyOffsets =
348 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
349 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
350 const VSyncModulator::Offsets earlyGlOffsets =
351 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
352 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
353 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
354 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700355
Romain Guy11d63f42017-07-20 12:47:14 -0700356 // We should be reading 'persist.sys.sf.color_saturation' here
357 // but since /data may be encrypted, we need to wait until after vold
358 // comes online to attempt to read the property. The property is
359 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800360
361 if (useTrebleTestingOverride()) {
362 // Without the override SurfaceFlinger cannot connect to HIDL
363 // services that are not listed in the manifests. Considered
364 // deriving the setting from the set service name, but it
365 // would be brittle if the name that's not 'default' is used
366 // for production purposes later on.
367 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
368 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800369}
370
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800371void SurfaceFlinger::onFirstRef()
372{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800373 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800374}
375
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376SurfaceFlinger::~SurfaceFlinger()
377{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378}
379
Dan Stozac7014012014-02-14 15:03:43 -0800380void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800381{
382 // the window manager died on us. prepare its eulogy.
383
Andy McFadden13a082e2012-08-24 10:16:42 -0700384 // restore initial conditions (default device unblank, etc)
385 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800386
387 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700388 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800389}
390
Robert Carr1db73f62016-12-21 12:58:51 -0800391static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700392 status_t err = client->initCheck();
393 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800394 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800395 }
Robert Carr1db73f62016-12-21 12:58:51 -0800396 return nullptr;
397}
398
399sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
400 return initClient(new Client(this));
401}
402
403sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
404 const sp<IGraphicBufferProducer>& gbp) {
405 if (authenticateSurfaceTexture(gbp) == false) {
406 return nullptr;
407 }
408 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
409 if (layer == nullptr) {
410 return nullptr;
411 }
412
413 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414}
415
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700416sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
417 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700418{
419 class DisplayToken : public BBinder {
420 sp<SurfaceFlinger> flinger;
421 virtual ~DisplayToken() {
422 // no more references, this display must be terminated
423 Mutex::Autolock _l(flinger->mStateLock);
424 flinger->mCurrentState.displays.removeItem(this);
425 flinger->setTransactionFlags(eDisplayTransactionNeeded);
426 }
427 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700428 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700429 : flinger(flinger) {
430 }
431 };
432
433 sp<BBinder> token = new DisplayToken(this);
434
435 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700436 DisplayDeviceState info;
437 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700438 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700439 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800441 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700442 return token;
443}
444
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700445void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700446 Mutex::Autolock _l(mStateLock);
447
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700448 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700449 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700450 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700451 return;
452 }
453
454 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700455 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700456 ALOGE("destroyDisplay called for non-virtual display");
457 return;
458 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700459 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700460 mCurrentState.displays.removeItemsAt(idx);
461 setTransactionFlags(eDisplayTransactionNeeded);
462}
463
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700465 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700466 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800467 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700468 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700469 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470}
471
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800472void SurfaceFlinger::bootFinished()
473{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700474 if (mStartPropertySetThread->join() != NO_ERROR) {
475 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800476 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800477 const nsecs_t now = systemTime();
478 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000479 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700480
481 // wait patiently for the window manager death
482 const String16 name("window");
483 sp<IBinder> window(defaultServiceManager()->getService(name));
484 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700485 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700486 }
487
Steven Thomas050b2c82017-03-06 11:45:16 -0800488 if (mVrFlinger) {
489 mVrFlinger->OnBootFinished();
490 }
491
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700492 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700493 // formerly we would just kill the process, but we now ask it to exit so it
494 // can choose where to stop the animation.
495 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700496
497 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
498 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
499 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700500
Dominik Laskowski8c001672018-05-30 16:52:06 -0700501 postMessageAsync(new LambdaMessage([this] { readPersistentProperties(); }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800502}
503
Mathias Agopian3f844832013-08-07 21:24:32 -0700504void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700505 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700506}
507
Lloyd Piquee83f9312018-02-01 12:53:17 -0800508class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700509public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700510 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000511 const char* name) :
512 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700513 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700514 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000515 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
516 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700517 mDispSync(dispSync),
518 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700519 mVsyncMutex(),
520 mPhaseOffset(phaseOffset),
521 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700522
Lloyd Piquee83f9312018-02-01 12:53:17 -0800523 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700524
Lloyd Piquee83f9312018-02-01 12:53:17 -0800525 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700526 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700527 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000528 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700529 static_cast<DispSync::Callback*>(this));
530 if (err != NO_ERROR) {
531 ALOGE("error registering vsync callback: %s (%d)",
532 strerror(-err), err);
533 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700534 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700535 } else {
536 status_t err = mDispSync->removeEventListener(
537 static_cast<DispSync::Callback*>(this));
538 if (err != NO_ERROR) {
539 ALOGE("error unregistering vsync callback: %s (%d)",
540 strerror(-err), err);
541 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700542 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700543 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700544 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700545 }
546
Lloyd Piquee83f9312018-02-01 12:53:17 -0800547 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700548 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700549 mCallback = callback;
550 }
551
Lloyd Piquee83f9312018-02-01 12:53:17 -0800552 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700553 Mutex::Autolock lock(mVsyncMutex);
554
555 // Normalize phaseOffset to [0, period)
556 auto period = mDispSync->getPeriod();
557 phaseOffset %= period;
558 if (phaseOffset < 0) {
559 // If we're here, then phaseOffset is in (-period, 0). After this
560 // operation, it will be in (0, period)
561 phaseOffset += period;
562 }
563 mPhaseOffset = phaseOffset;
564
565 // If we're not enabled, we don't need to mess with the listeners
566 if (!mEnabled) {
567 return;
568 }
569
Dan Stoza84d619e2018-03-28 17:07:36 -0700570 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
571 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700572 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700573 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700574 strerror(-err), err);
575 }
576 }
577
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700578private:
579 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800580 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700581 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700582 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700583 callback = mCallback;
584
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700585 if (mTraceVsync) {
586 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700587 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700588 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589 }
590
Peiyong Lin566a3b42018-01-09 18:22:43 -0800591 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700592 callback->onVSyncEvent(when);
593 }
594 }
595
Tim Murray4a4e4a22016-04-19 16:29:23 +0000596 const char* const mName;
597
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700598 int mValue;
599
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700600 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700601 const String8 mVsyncOnLabel;
602 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700603
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700605
606 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800607 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700608
609 Mutex mVsyncMutex; // Protects the following
610 nsecs_t mPhaseOffset;
611 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700612};
613
Lloyd Piquee83f9312018-02-01 12:53:17 -0800614class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700615public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800616 InjectVSyncSource() = default;
617 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700618
Lloyd Piquee83f9312018-02-01 12:53:17 -0800619 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700620 std::lock_guard<std::mutex> lock(mCallbackMutex);
621 mCallback = callback;
622 }
623
Lloyd Piquee83f9312018-02-01 12:53:17 -0800624 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700625 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700626 if (mCallback) {
627 mCallback->onVSyncEvent(when);
628 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700629 }
630
Lloyd Piquee83f9312018-02-01 12:53:17 -0800631 void setVSyncEnabled(bool) override {}
632 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700633
634private:
635 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800636 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700637};
638
Wei Wangf9b05ee2017-07-19 20:59:39 -0700639// Do not call property_set on main thread which will be blocked by init
640// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700641void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700642 ALOGI( "SurfaceFlinger's main thread ready to run. "
643 "Initializing graphics H/W...");
644
Thierry Strudel2924d012017-08-14 15:19:37 -0700645 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900646
Steven Thomasb02664d2017-07-26 18:48:28 -0700647 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800648
Steven Thomasb02664d2017-07-26 18:48:28 -0700649 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800650 mEventThreadSource =
651 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
652 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800653 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700654 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800655 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800656 "appEventThread");
657 mSfEventThreadSource =
658 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
659 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800660
Lloyd Pique24b0a482018-03-09 18:52:26 -0800661 mSFEventThread =
662 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700663 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800664 [this](nsecs_t timestamp) {
665 mInterceptor->saveVSyncEvent(timestamp);
666 },
667 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800668 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200669 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800670
Steven Thomasb02664d2017-07-26 18:48:28 -0700671 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800672 getBE().mRenderEngine =
673 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
674 hasWideColorDisplay
675 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
676 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800677 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700678
679 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
680 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800681 getBE().mHwc.reset(
682 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700683 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800684 // Process any initial hotplug and resulting display changes.
685 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700686 const auto display = getDefaultDisplayDeviceLocked();
687 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
688 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
689 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800690
Lloyd Piquefcd86612017-12-14 17:15:36 -0800691 // make the default display GLContext current so that we can create textures
692 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700693 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800694
Steven Thomas050b2c82017-03-06 11:45:16 -0800695 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700696 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700697 // This callback is called from the vr flinger dispatch thread. We
698 // need to call signalTransaction(), which requires holding
699 // mStateLock when we're not on the main thread. Acquiring
700 // mStateLock from the vr flinger dispatch thread might trigger a
701 // deadlock in surface flinger (see b/66916578), so post a message
702 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700703 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700704 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
705 mVrFlingerRequestsDisplay = requestDisplay;
706 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700707 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800708 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700709 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
710 getHwComposer()
711 .getHwcDisplayId(display->getId())
712 .value_or(0),
713 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800714 if (!mVrFlinger) {
715 ALOGE("Failed to start vrflinger");
716 }
717 }
718
Lloyd Pique379adc12018-01-22 17:31:47 -0800719 mEventControlThread = std::make_unique<impl::EventControlThread>(
720 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700721
Mathias Agopian92a979a2012-08-02 18:32:23 -0700722 // initialize our drawing state
723 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700724
Andy McFadden13a082e2012-08-24 10:16:42 -0700725 // set initial conditions (e.g. unblank default device)
726 initializeDisplays();
727
David Sodmanbc815282017-11-05 18:57:52 -0800728 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700729
Wei Wangf9b05ee2017-07-19 20:59:39 -0700730 // Inform native graphics APIs whether the present timestamp is supported:
731 if (getHwComposer().hasCapability(
732 HWC2::Capability::PresentFenceIsNotReliable)) {
733 mStartPropertySetThread = new StartPropertySetThread(false);
734 } else {
735 mStartPropertySetThread = new StartPropertySetThread(true);
736 }
737
738 if (mStartPropertySetThread->Start() != NO_ERROR) {
739 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800740 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800741
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700742 mLegacySrgbSaturationMatrix =
743 getHwComposer().getDataspaceSaturationMatrix(display->getId(), Dataspace::SRGB_LINEAR);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800744
Dan Stoza9e56aa02015-11-02 13:00:03 -0800745 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700746}
747
Romain Guy11d63f42017-07-20 12:47:14 -0700748void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700749 Mutex::Autolock _l(mStateLock);
750
Romain Guy11d63f42017-07-20 12:47:14 -0700751 char value[PROPERTY_VALUE_MAX];
752
753 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800754 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700755 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800756 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100757
758 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700759 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700760}
761
Mathias Agopiana67e4182012-06-19 17:26:12 -0700762void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800763 // Start boot animation service by setting a property mailbox
764 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700765 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800766 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700767 if (mStartPropertySetThread->join() != NO_ERROR) {
768 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800769 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700770}
771
Mathias Agopian875d8e12013-06-07 15:35:48 -0700772size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800773 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700774}
775
Mathias Agopian875d8e12013-06-07 15:35:48 -0700776size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800777 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700778}
779
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800780// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800781
Jamie Gennis582270d2011-08-17 18:19:00 -0700782bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800783 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800784 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800785 return authenticateSurfaceTextureLocked(bufferProducer);
786}
787
788bool SurfaceFlinger::authenticateSurfaceTextureLocked(
789 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800790 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800791 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800792}
793
Brian Anderson6b376712017-04-04 10:51:39 -0700794status_t SurfaceFlinger::getSupportedFrameTimestamps(
795 std::vector<FrameEvent>* outSupported) const {
796 *outSupported = {
797 FrameEvent::REQUESTED_PRESENT,
798 FrameEvent::ACQUIRE,
799 FrameEvent::LATCH,
800 FrameEvent::FIRST_REFRESH_START,
801 FrameEvent::LAST_REFRESH_START,
802 FrameEvent::GPU_COMPOSITION_DONE,
803 FrameEvent::DEQUEUE_READY,
804 FrameEvent::RELEASE,
805 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700806 ConditionalLock _l(mStateLock,
807 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700808 if (!getHwComposer().hasCapability(
809 HWC2::Capability::PresentFenceIsNotReliable)) {
810 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
811 }
812 return NO_ERROR;
813}
814
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700815status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
816 Vector<DisplayInfo>* configs) {
817 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700818 return BAD_VALUE;
819 }
820
Jesse Hall692c7232012-11-08 15:41:56 -0800821 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700822 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
823 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700824 type = i;
825 break;
826 }
827 }
828
829 if (type < 0) {
830 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700831 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 // TODO: Not sure if display density should handled by SF any longer
834 class Density {
835 static int getDensityFromProperty(char const* propName) {
836 char property[PROPERTY_VALUE_MAX];
837 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800838 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 density = atoi(property);
840 }
841 return density;
842 }
843 public:
844 static int getEmuDensity() {
845 return getDensityFromProperty("qemu.sf.lcd_density"); }
846 static int getBuildDensity() {
847 return getDensityFromProperty("ro.sf.lcd_density"); }
848 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700849
Dan Stoza7f7da322014-05-02 15:26:25 -0700850 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700851
Steven Thomas6d8110b2017-08-31 18:24:21 -0700852 ConditionalLock _l(mStateLock,
853 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800854 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700855 DisplayInfo info = DisplayInfo();
856
Dan Stoza9e56aa02015-11-02 13:00:03 -0800857 float xdpi = hwConfig->getDpiX();
858 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700859
860 if (type == DisplayDevice::DISPLAY_PRIMARY) {
861 // The density of the device is provided by a build property
862 float density = Density::getBuildDensity() / 160.0f;
863 if (density == 0) {
864 // the build doesn't provide a density -- this is wrong!
865 // use xdpi instead
866 ALOGE("ro.sf.lcd_density must be defined as a build property");
867 density = xdpi / 160.0f;
868 }
869 if (Density::getEmuDensity()) {
870 // if "qemu.sf.lcd_density" is specified, it overrides everything
871 xdpi = ydpi = density = Density::getEmuDensity();
872 density /= 160.0f;
873 }
874 info.density = density;
875
876 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700877 const auto display = getDefaultDisplayDeviceLocked();
878 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700879 } else {
880 // TODO: where should this value come from?
881 static const int TV_DENSITY = 213;
882 info.density = TV_DENSITY / 160.0f;
883 info.orientation = 0;
884 }
885
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 info.w = hwConfig->getWidth();
887 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700888 info.xdpi = xdpi;
889 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900891 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892
Andy McFadden91b2ca82014-06-13 14:04:23 -0700893 // This is how far in advance a buffer must be queued for
894 // presentation at a given time. If you want a buffer to appear
895 // on the screen at time N, you must submit the buffer before
896 // (N - presentationDeadline).
897 //
898 // Normally it's one full refresh period (to give SF a chance to
899 // latch the buffer), but this can be reduced by configuring a
900 // DispSync offset. Any additional delays introduced by the hardware
901 // composer or panel must be accounted for here.
902 //
903 // We add an additional 1ms to allow for processing time and
904 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800905 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800906 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700907
908 // All non-virtual displays are currently considered secure.
909 info.secure = true;
910
Iris Chang7501ed62018-04-30 14:45:42 +0800911 if (type == DisplayDevice::DISPLAY_PRIMARY &&
912 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
913 std::swap(info.w, info.h);
914 }
915
Michael Wright28f24d02016-07-12 13:30:53 -0700916 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700917 }
918
Dan Stoza7f7da322014-05-02 15:26:25 -0700919 return NO_ERROR;
920}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
923 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700924 return BAD_VALUE;
925 }
926
927 // FIXME for now we always return stats for the primary display
928 memset(stats, 0, sizeof(*stats));
929 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
930 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
931 return NO_ERROR;
932}
933
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700934int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
935 const auto display = getDisplayDevice(displayToken);
936 if (!display) {
937 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800938 return BAD_VALUE;
939 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700940
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700941 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700942}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700943
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700944void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
945 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700946 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700947 return;
948 }
949
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700950 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700951 ALOGW("Trying to set config for virtual display");
952 return;
953 }
954
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700955 display->setActiveConfig(mode);
956 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700957}
958
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700959status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700960 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700961 Vector<DisplayInfo> configs;
962 getDisplayConfigs(displayToken, &configs);
963 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
964 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
965 configs.size());
966 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700967 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700968 const auto display = getDisplayDevice(displayToken);
969 if (!display) {
970 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
971 displayToken.get());
972 } else if (display->isVirtual()) {
973 ALOGW("Attempt to set active config %d for virtual display", mode);
974 } else {
975 setActiveConfigInternal(display, mode);
976 }
977 }));
978
Mathias Agopian888c8222012-08-04 21:10:38 -0700979 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700980}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700981status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
982 Vector<ColorMode>* outColorModes) {
983 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700984 return BAD_VALUE;
985 }
986
Michael Wright28f24d02016-07-12 13:30:53 -0700987 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700988 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
989 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700990 type = i;
991 break;
992 }
993 }
994
995 if (type < 0) {
996 return type;
997 }
998
Peiyong Lina52f0292018-03-14 17:26:31 -0700999 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001000 {
1001 ConditionalLock _l(mStateLock,
1002 std::this_thread::get_id() != mMainThreadId);
1003 modes = getHwComposer().getColorModes(type);
1004 }
Michael Wright28f24d02016-07-12 13:30:53 -07001005 outColorModes->clear();
1006 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1007
1008 return NO_ERROR;
1009}
1010
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001011ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1012 if (const auto display = getDisplayDevice(displayToken)) {
1013 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001014 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001015 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001016}
1017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1019 Dataspace dataSpace, RenderIntent renderIntent) {
1020 ColorMode currentMode = display->getActiveColorMode();
1021 Dataspace currentDataSpace = display->getCompositionDataSpace();
1022 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001023
Peiyong Lin38e9a562018-04-10 16:24:20 -07001024 if (mode == currentMode && dataSpace == currentDataSpace &&
1025 renderIntent == currentRenderIntent) {
1026 return;
1027 }
1028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001030 ALOGW("Trying to set config for virtual display");
1031 return;
1032 }
1033
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001034 display->setActiveColorMode(mode);
1035 display->setCompositionDataSpace(dataSpace);
1036 display->setActiveRenderIntent(renderIntent);
1037 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001038
1039 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001040 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1041 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001042}
1043
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001044status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001045 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001046 Vector<ColorMode> modes;
1047 getDisplayColorModes(displayToken, &modes);
1048 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1049 if (mode < ColorMode::NATIVE || !exists) {
1050 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1051 decodeColorMode(mode).c_str(), mode, displayToken.get());
1052 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001053 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001054 const auto display = getDisplayDevice(displayToken);
1055 if (!display) {
1056 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1057 decodeColorMode(mode).c_str(), mode, displayToken.get());
1058 } else if (display->isVirtual()) {
1059 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1060 decodeColorMode(mode).c_str(), mode);
1061 } else {
1062 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1063 RenderIntent::COLORIMETRIC);
1064 }
1065 }));
1066
Michael Wright28f24d02016-07-12 13:30:53 -07001067 return NO_ERROR;
1068}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001069
Svetoslavd85084b2014-03-20 10:28:31 -07001070status_t SurfaceFlinger::clearAnimationFrameStats() {
1071 Mutex::Autolock _l(mStateLock);
1072 mAnimFrameTracker.clearStats();
1073 return NO_ERROR;
1074}
1075
1076status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1077 Mutex::Autolock _l(mStateLock);
1078 mAnimFrameTracker.getStats(outStats);
1079 return NO_ERROR;
1080}
1081
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001082status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1083 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001084 Mutex::Autolock _l(mStateLock);
1085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086 const auto display = getDisplayDeviceLocked(displayToken);
1087 if (!display) {
1088 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001089 return BAD_VALUE;
1090 }
1091
Peiyong Linfb069302018-04-25 14:34:31 -07001092 // At this point the DisplayDeivce should already be set up,
1093 // meaning the luminance information is already queried from
1094 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001095 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001096 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1097 capabilities.getDesiredMaxLuminance(),
1098 capabilities.getDesiredMaxAverageLuminance(),
1099 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001100
1101 return NO_ERROR;
1102}
1103
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001104status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001105 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001106 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001107
Chia-I Wu90f669f2017-10-05 14:24:41 -07001108 if (mInjectVSyncs == enable) {
1109 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001110 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001111
1112 if (enable) {
1113 ALOGV("VSync Injections enabled");
1114 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001115 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001116 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001117 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001118 impl::EventThread::InterceptVSyncsCallback(),
1119 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001120 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001121 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001122 } else {
1123 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001124 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001125 }
1126
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001127 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001128 }));
1129
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001130 return NO_ERROR;
1131}
1132
1133status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001134 Mutex::Autolock _l(mStateLock);
1135
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001136 if (!mInjectVSyncs) {
1137 ALOGE("VSync Injections not enabled");
1138 return BAD_VALUE;
1139 }
1140 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1141 ALOGV("Injecting VSync inside SurfaceFlinger");
1142 mVSyncInjector->onInjectSyncEvent(when);
1143 }
1144 return NO_ERROR;
1145}
1146
Lloyd Pique755e3192018-01-31 16:46:15 -08001147status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1148 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001149 IPCThreadState* ipc = IPCThreadState::self();
1150 const int pid = ipc->getCallingPid();
1151 const int uid = ipc->getCallingUid();
1152 if ((uid != AID_SHELL) &&
1153 !PermissionCache::checkPermission(sDump, pid, uid)) {
1154 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1155 return PERMISSION_DENIED;
1156 }
1157
1158 // Try to acquire a lock for 1s, fail gracefully
1159 const status_t err = mStateLock.timedLock(s2ns(1));
1160 const bool locked = (err == NO_ERROR);
1161 if (!locked) {
1162 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1163 return TIMED_OUT;
1164 }
1165
1166 outLayers->clear();
1167 mCurrentState.traverseInZOrder([&](Layer* layer) {
1168 outLayers->push_back(layer->getLayerDebugInfo());
1169 });
1170
1171 mStateLock.unlock();
1172 return NO_ERROR;
1173}
1174
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001175// ----------------------------------------------------------------------------
1176
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001177sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1178 ISurfaceComposer::VsyncSource vsyncSource) {
1179 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1180 return mSFEventThread->createEventConnection();
1181 } else {
1182 return mEventThread->createEventConnection();
1183 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001184}
1185
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001186// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001187
1188void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001189 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001190}
1191
1192void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001193 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001194}
1195
1196void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001197 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001198}
1199
1200void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001201 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001202 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001203}
1204
1205status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001206 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001207 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001208}
1209
1210status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001211 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001212 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001213 if (res == NO_ERROR) {
1214 msg->wait();
1215 }
1216 return res;
1217}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001218
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001219void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001220 do {
1221 waitForEvent();
1222 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001223}
1224
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225void SurfaceFlinger::enableHardwareVsync() {
1226 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001227 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001229 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001230 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001231 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001232}
1233
Jesse Hall948fe0c2013-10-14 12:56:09 -07001234void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001235 Mutex::Autolock _l(mHWVsyncLock);
1236
Jesse Hall948fe0c2013-10-14 12:56:09 -07001237 if (makeAvailable) {
1238 mHWVsyncAvailable = true;
1239 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001240 // Hardware vsync is not currently available, so abort the resync
1241 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001242 return;
1243 }
1244
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001245 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1246 if (!getHwComposer().isConnected(displayId)) {
1247 return;
1248 }
1249
1250 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001251 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001252
1253 mPrimaryDispSync.reset();
1254 mPrimaryDispSync.setPeriod(period);
1255
1256 if (!mPrimaryHWVsyncEnabled) {
1257 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001258 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001259 mPrimaryHWVsyncEnabled = true;
1260 }
1261}
1262
Jesse Hall948fe0c2013-10-14 12:56:09 -07001263void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264 Mutex::Autolock _l(mHWVsyncLock);
1265 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001266 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267 mPrimaryDispSync.endResync();
1268 mPrimaryHWVsyncEnabled = false;
1269 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001270 if (makeUnavailable) {
1271 mHWVsyncAvailable = false;
1272 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273}
1274
Tim Murray4a4e4a22016-04-19 16:29:23 +00001275void SurfaceFlinger::resyncWithRateLimit() {
1276 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001277
1278 // No explicit locking is needed here since EventThread holds a lock while calling this method
1279 static nsecs_t sLastResyncAttempted = 0;
1280 const nsecs_t now = systemTime();
1281 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001282 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001283 }
Dan Stoza57164302017-05-08 14:03:54 -07001284 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001285}
1286
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001287void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1288 int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001289 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001290 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001291 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001292 return;
1293 }
1294
1295 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001296 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001297 return;
1298 }
1299
Jamie Gennisd1700752013-10-14 12:22:52 -07001300 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001301
Jamie Gennisd1700752013-10-14 12:22:52 -07001302 { // Scope for the lock
1303 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001304 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001305 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001306 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001307 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001308
1309 if (needsHwVsync) {
1310 enableHardwareVsync();
1311 } else {
1312 disableHardwareVsync(false);
1313 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001314}
1315
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001316void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001317 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1318 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001319}
1320
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001321void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001322 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001323 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001324 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001325
Lloyd Piqueba04e622017-12-14 17:11:26 -08001326 // Ignore events that do not have the right sequenceId.
1327 if (sequenceId != getBE().mComposerSequenceId) {
1328 return;
1329 }
1330
Steven Thomasb02664d2017-07-26 18:48:28 -07001331 // Only lock if we're not on the main thread. This function is normally
1332 // called on a hwbinder thread, but for the primary display it's called on
1333 // the main thread with the state lock already held, so don't attempt to
1334 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001335 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001336
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001337 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001338
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001339 if (std::this_thread::get_id() == mMainThreadId) {
1340 // Process all pending hot plug events immediately if we are on the main thread.
1341 processDisplayHotplugEventsLocked();
1342 }
1343
Lloyd Piqueba04e622017-12-14 17:11:26 -08001344 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001345}
1346
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001347void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001348 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001349 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001350 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001351 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001352 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001353}
1354
Dan Stoza9e56aa02015-11-02 13:00:03 -08001355void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001356 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001357 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001358 getHwComposer().setVsyncEnabled(disp,
1359 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001360}
1361
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001362// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001363void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001364 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001365 // Clear the drawing state so that the logic inside of
1366 // handleTransactionLocked will fire. It will determine the delta between
1367 // mCurrentState and mDrawingState and re-apply all changes when we make the
1368 // transition.
1369 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001370 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001371 mDisplays.clear();
1372}
1373
Steven Thomas050b2c82017-03-06 11:45:16 -08001374void SurfaceFlinger::updateVrFlinger() {
1375 if (!mVrFlinger)
1376 return;
1377 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001378 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001379 return;
1380 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001381
David Sodman105b7dc2017-11-04 20:28:14 -07001382 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 ALOGE("Vr flinger is only supported for remote hardware composer"
1384 " service connections. Ignoring request to transition to vr"
1385 " flinger.");
1386 mVrFlingerRequestsDisplay = false;
1387 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001388 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001389
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001390 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001391
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001392 const auto display = getDefaultDisplayDeviceLocked();
1393 LOG_ALWAYS_FATAL_IF(!display);
1394 const int currentDisplayPowerMode = display->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001395
Steven Thomasb02664d2017-07-26 18:48:28 -07001396 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001397 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001398 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001399
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001401 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001402 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1403 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001404 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001405
David Sodman105b7dc2017-11-04 20:28:14 -07001406 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1407 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001408
1409 if (vrFlingerRequestsDisplay) {
1410 mVrFlinger->GrantDisplayOwnership();
1411 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001412 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001413 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001414
1415 mVisibleRegionsDirty = true;
1416 invalidateHwcGeometry();
1417
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001418 // Re-enable default display.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001419 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001420
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001422 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001423 const nsecs_t period = activeConfig->getVsyncPeriod();
1424 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001425
Steven Thomasb02664d2017-07-26 18:48:28 -07001426 // Use phase of 0 since phase is not known.
1427 // Use latency of 0, which will snap to the ideal latency.
1428 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001429
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430 android_atomic_or(1, &mRepaintEverything);
1431 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001432}
1433
Mathias Agopian4fec8732012-06-29 14:12:52 -07001434void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001435 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001436 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001437 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001438 bool frameMissed = !mHadClientComposition &&
1439 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001440 (mPreviousPresentFence->getSignalTime() ==
1441 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001442 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001443 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001444 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001445 mTimeStats.incrementMissedFrames();
1446 if (mPropagateBackpressure) {
1447 signalLayerUpdate();
1448 break;
1449 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001450 }
Dan Stoza50182882016-07-08 12:02:20 -07001451
Steven Thomas050b2c82017-03-06 11:45:16 -08001452 // Now that we're going to make it to the handleMessageTransaction()
1453 // call below it's safe to call updateVrFlinger(), which will
1454 // potentially trigger a display handoff.
1455 updateVrFlinger();
1456
Dan Stoza6b9454d2014-11-07 16:00:59 -08001457 bool refreshNeeded = handleMessageTransaction();
1458 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001459 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001460 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001461 // Signal a refresh if a transaction modified the window state,
1462 // a new buffer was latched, or if HWC has requested a full
1463 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001464 signalRefresh();
1465 }
1466 break;
1467 }
1468 case MessageQueue::REFRESH: {
1469 handleMessageRefresh();
1470 break;
1471 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001472 }
1473}
1474
Dan Stoza6b9454d2014-11-07 16:00:59 -08001475bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001476 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001477 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001478 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001479 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001480 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001481 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001482}
1483
Dan Stoza6b9454d2014-11-07 16:00:59 -08001484bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001485 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001486 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001487}
1488
1489void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001490 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001491
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001492 mRefreshPending = false;
1493
Chia-I Wu30505fb2018-03-26 16:20:31 -07001494 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001495
Chia-I Wu30505fb2018-03-26 16:20:31 -07001496 preComposition(refreshStartTime);
1497 rebuildLayerStacks();
1498 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001499 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001500 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001501 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001502 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001503 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001504
Dan Stozabfbffeb2016-07-21 14:49:33 -07001505 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001506 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001507 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001508 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001509 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001510 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001511
Dan Stoza9e56aa02015-11-02 13:00:03 -08001512 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001513}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001514
Mathias Agopiancd60f992012-08-16 16:28:27 -07001515void SurfaceFlinger::doDebugFlashRegions()
1516{
1517 // is debugging enabled
1518 if (CC_LIKELY(!mDebugRegion))
1519 return;
1520
1521 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001522 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001523 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001525 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001526 if (!dirtyRegion.isEmpty()) {
1527 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001528 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001529
1530 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001531 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001532 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001533 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1534
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001535 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001536 }
1537 }
1538 }
1539
1540 postFramebuffer();
1541
1542 if (mDebugRegion > 1) {
1543 usleep(mDebugRegion * 1000);
1544 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001545
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()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001548 continue;
1549 }
1550
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001551 status_t result = display->prepareFrame(*getBE().mHwc);
1552 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001553 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001554 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555}
1556
Adrian Roos1e1a1282017-11-01 19:05:31 +01001557void SurfaceFlinger::doTracing(const char* where) {
1558 ATRACE_CALL();
1559 ATRACE_NAME(where);
1560 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001561 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001562 }
1563}
1564
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001565void SurfaceFlinger::logLayerStats() {
1566 ATRACE_CALL();
1567 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001568 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001569 if (display->isPrimary()) {
1570 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001571 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001572 }
1573 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001574
1575 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001576 }
1577}
1578
Chia-I Wu30505fb2018-03-26 16:20:31 -07001579void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001580{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001581 ATRACE_CALL();
1582 ALOGV("preComposition");
1583
Mathias Agopiancd60f992012-08-16 16:28:27 -07001584 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001585 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001586 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587 needExtraInvalidate = true;
1588 }
Robert Carr2047fae2016-11-28 14:09:09 -08001589 });
1590
Mathias Agopiancd60f992012-08-16 16:28:27 -07001591 if (needExtraInvalidate) {
1592 signalLayerUpdate();
1593 }
1594}
1595
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001596void SurfaceFlinger::updateCompositorTiming(
1597 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1598 std::shared_ptr<FenceTime>& presentFenceTime) {
1599 // Update queue of past composite+present times and determine the
1600 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001601 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001602 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001603 while (!getBE().mCompositePresentTimes.empty()) {
1604 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001605 // Cached values should have been updated before calling this method,
1606 // which helps avoid duplicate syscalls.
1607 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1608 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1609 break;
1610 }
1611 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001612 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001613 }
1614
1615 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001616 while (getBE().mCompositePresentTimes.size() > 16) {
1617 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001618 }
1619
Brian Andersond0010582017-03-07 13:20:31 -08001620 setCompositorTimingSnapped(
1621 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1622}
1623
1624void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1625 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001626 // Integer division and modulo round toward 0 not -inf, so we need to
1627 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001628 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001629 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1630 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1631
Brian Andersond0010582017-03-07 13:20:31 -08001632 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1633 if (idealLatency <= 0) {
1634 idealLatency = vsyncInterval;
1635 }
1636
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001637 // Snap the latency to a value that removes scheduling jitter from the
1638 // composition and present times, which often have >1ms of jitter.
1639 // Reducing jitter is important if an app attempts to extrapolate
1640 // something (such as user input) to an accurate diasplay time.
1641 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1642 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001643 nsecs_t bias = vsyncInterval / 2;
1644 int64_t extraVsyncs =
1645 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1646 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1647 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001648
David Sodman99974d22017-11-28 12:04:33 -08001649 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1650 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1651 getBE().mCompositorTiming.interval = vsyncInterval;
1652 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001653}
1654
Chia-I Wu30505fb2018-03-26 16:20:31 -07001655void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001656{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001657 ATRACE_CALL();
1658 ALOGV("postComposition");
1659
Brian Anderson3546a3f2016-07-14 11:51:14 -07001660 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001661 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001662 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001663 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001664 }
1665
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001666 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001667 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001668
David Sodman73beded2017-11-15 11:56:06 -08001669 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001670 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001671 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001672 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001673 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001674 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001675 } else {
1676 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1677 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001678
David Sodman73beded2017-11-15 11:56:06 -08001679 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001680 mPreviousPresentFence =
1681 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1682 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001683 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001684
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001685 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1686 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1687
Chia-I Wu30505fb2018-03-26 16:20:31 -07001688 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001689 // when we started doing work for this frame, but that should be okay
1690 // since updateCompositorTiming has snapping logic.
1691 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001692 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001693 CompositorTiming compositorTiming;
1694 {
David Sodman99974d22017-11-28 12:04:33 -08001695 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1696 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001697 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001698
Robert Carr2047fae2016-11-28 14:09:09 -08001699 mDrawingState.traverseInZOrder([&](Layer* layer) {
1700 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001701 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001702 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001703 recordBufferingStats(layer->getName().string(),
1704 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001705 }
Robert Carr2047fae2016-11-28 14:09:09 -08001706 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001707
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001708 if (presentFenceTime->isValid()) {
1709 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001710 enableHardwareVsync();
1711 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001712 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001713 }
1714 }
1715
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001716 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001717 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001718 enableHardwareVsync();
1719 }
1720 }
1721
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001722 if (mAnimCompositionPending) {
1723 mAnimCompositionPending = false;
1724
Brian Anderson4e606e32017-03-16 15:34:57 -07001725 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001726 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001727 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001728 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001729 // The HWC doesn't support present fences, so use the refresh
1730 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001731 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001732 mAnimFrameTracker.setActualPresentTime(presentTime);
1733 }
1734 mAnimFrameTracker.advanceFrame();
1735 }
Dan Stozab90cf072015-03-05 11:05:59 -08001736
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001737 mTimeStats.incrementTotalFrames();
1738 if (mHadClientComposition) {
1739 mTimeStats.incrementClientCompositionFrames();
1740 }
1741
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001742 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001743 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001744 return;
1745 }
1746
1747 nsecs_t currentTime = systemTime();
1748 if (mHasPoweredOff) {
1749 mHasPoweredOff = false;
1750 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001751 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001752 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001753 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1754 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001755 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001756 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001757 }
David Sodman4a36e932017-11-07 14:29:47 -08001758 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001759 }
David Sodman4a36e932017-11-07 14:29:47 -08001760 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001761}
1762
1763void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001764 ATRACE_CALL();
1765 ALOGV("rebuildLayerStacks");
1766
Mathias Agopiancd60f992012-08-16 16:28:27 -07001767 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001768 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001769 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001770 mVisibleRegionsDirty = false;
1771 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001772
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001773 for (const auto& pair : mDisplays) {
1774 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001775 Region opaqueRegion;
1776 Region dirtyRegion;
1777 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001778 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001779 const Transform& tr = display->getTransform();
1780 const Rect bounds = display->getBounds();
1781 if (display->isPoweredOn()) {
1782 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001783
Jeff Sharkey76488112017-02-27 14:15:18 -07001784 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001785 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001786 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001787 Region drawRegion(tr.transform(
1788 layer->visibleNonTransparentRegion));
1789 drawRegion.andSelf(bounds);
1790 if (!drawRegion.isEmpty()) {
1791 layersSortedByZ.add(layer);
1792 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001793 // Clear out the HWC layer if this layer was
1794 // previously visible, but no longer is
Dominik Laskowski7e045462018-05-30 13:02:02 -07001795 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001796 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001797 } else {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001798 // WM changes display->layerStack upon sleep/awake.
Chia-I Wu30505fb2018-03-26 16:20:31 -07001799 // Here we make sure we delete the HWC layers even if
1800 // WM changed their layer stack.
Dominik Laskowski7e045462018-05-30 13:02:02 -07001801 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001802 }
1803
1804 // If a layer is not going to get a release fence because
1805 // it is invisible, but it is also going to release its
1806 // old buffer, add it to the list of layers needing
1807 // fences.
1808 if (hwcLayerDestroyed) {
1809 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1810 mLayersWithQueuedFrames.cend(), layer);
1811 if (found != mLayersWithQueuedFrames.cend()) {
1812 layersNeedingFences.add(layer);
1813 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001814 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001815 });
1816 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001817 display->setVisibleLayersSortedByZ(layersSortedByZ);
1818 display->setLayersNeedingFences(layersNeedingFences);
1819 display->undefinedRegion.set(bounds);
1820 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1821 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001822 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001823 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001824}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001825
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001826// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001827// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001828// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001829// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001830// The returned HDR data space is one of
1831// - Dataspace::UNKNOWN
1832// - Dataspace::BT2020_HLG
1833// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001834Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1835 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001836 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001837 *outHdrDataSpace = Dataspace::UNKNOWN;
1838
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001839 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001840 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001841 case Dataspace::V0_SCRGB:
1842 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001843 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001844 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001845 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001846 case Dataspace::BT2020_PQ:
1847 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001848 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001849 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001850 case Dataspace::BT2020_HLG:
1851 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001852 // When there's mixed PQ content and HLG content, we set the HDR
1853 // data space to be BT2020_PQ and convert HLG to PQ.
1854 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1855 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001856 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001857 break;
1858 default:
1859 break;
1860 }
Romain Guy54f154a2017-10-24 21:40:32 +01001861 }
1862
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001863 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001864}
1865
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001866// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001867void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1868 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001869 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1870 *outMode = ColorMode::NATIVE;
1871 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001872 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001873 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001874 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001875
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001876 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001877 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001878
Peiyong Lindfde5112018-06-05 10:58:41 -07001879 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001880 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001881 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001882 if (isHdr) {
1883 bestDataSpace = hdrDataSpace;
1884 }
1885
Chia-I Wu0d711262018-05-21 15:19:35 -07001886 RenderIntent intent;
1887 switch (mDisplayColorSetting) {
1888 case DisplayColorSetting::MANAGED:
1889 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001890 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001891 break;
1892 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001893 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001894 break;
1895 default: // vendor display color setting
1896 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1897 break;
1898 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001899
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001900 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001901}
1902
Chia-I Wu30505fb2018-03-26 16:20:31 -07001903void SurfaceFlinger::setUpHWComposer() {
1904 ATRACE_CALL();
1905 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001906
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001907 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001908 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
1909 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1910 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07001911
1912 // If nothing has changed (!dirty), don't recompose.
1913 // If something changed, but we don't currently have any visible layers,
1914 // and didn't when we last did a composition, then skip it this time.
1915 // The second rule does two things:
1916 // - When all layers are removed from a display, we'll emit one black
1917 // frame, then nothing more until we get new layers.
1918 // - When a display is created with a private layer stack, we won't
1919 // emit any black frames until a layer is added to the layer stack.
1920 bool mustRecompose = dirty && !(empty && wasEmpty);
1921
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001922 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001923 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
1924 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07001925
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001926 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001927
1928 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001929 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07001930 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001931 }
1932
Chia-I Wu30505fb2018-03-26 16:20:31 -07001933 // build the h/w work list
1934 if (CC_UNLIKELY(mGeometryInvalid)) {
1935 mGeometryInvalid = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001936 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001937 const auto displayId = display->getId();
1938 if (displayId >= 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001939 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001940 for (size_t i = 0; i < currentLayers.size(); i++) {
1941 const auto& layer = currentLayers[i];
Dominik Laskowski7e045462018-05-30 13:02:02 -07001942 if (!layer->hasHwcLayer(displayId)) {
1943 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1944 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001945 continue;
1946 }
1947 }
1948
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001949 layer->setGeometry(display, i);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001950 if (mDebugDisableHWC || mDebugRegion) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001951 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001952 }
1953 }
1954 }
1955 }
1956 }
1957
Chia-I Wu30505fb2018-03-26 16:20:31 -07001958 // Set the per-frame data
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001959 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001960 const auto displayId = display->getId();
1961 if (displayId < 0) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001962 continue;
1963 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07001964
Chia-I Wu28f320b2018-05-03 11:02:56 -07001965 if (mDrawingState.colorMatrixChanged) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001966 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski7e045462018-05-30 13:02:02 -07001967 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001968 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001969 displayId, result);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001970 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001971 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu692e0832018-06-05 15:46:58 -07001972 if (layer->isHdrY410()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001973 layer->forceClientComposition(displayId);
Chia-I Wu692e0832018-06-05 15:46:58 -07001974 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1975 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1976 !display->hasHDR10Support()) {
1977 layer->forceClientComposition(displayId);
1978 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1979 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1980 !display->hasHLGSupport()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001981 layer->forceClientComposition(displayId);
Peiyong Linf59a7192018-04-25 11:19:31 -07001982 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001983
Dominik Laskowski7e045462018-05-30 13:02:02 -07001984 if (layer->getForceClientComposition(displayId)) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001985 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07001986 layer->setCompositionType(displayId, HWC2::Composition::Client);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001987 continue;
1988 }
1989
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001990 layer->setPerFrameData(display);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001991 }
1992
1993 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001994 ColorMode colorMode;
1995 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001996 RenderIntent renderIntent;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001997 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1998 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001999 }
2000 }
2001
Chia-I Wu28f320b2018-05-03 11:02:56 -07002002 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07002003
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002004 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002005 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002006 continue;
2007 }
2008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002009 status_t result = display->prepareFrame(*getBE().mHwc);
2010 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002011 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002012 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002013}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002014
Mathias Agopiancd60f992012-08-16 16:28:27 -07002015void SurfaceFlinger::doComposition() {
2016 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 ALOGV("doComposition");
2018
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002019 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002020 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002021 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002022 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002023 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002024
2025 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002026 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002028 display->dirtyRegion.clear();
2029 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002030 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002031 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002032 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002033}
2034
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002035void SurfaceFlinger::postFramebuffer()
2036{
Mathias Agopian841cde52012-03-01 15:44:37 -08002037 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002038 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002039
Mathias Agopiana44b0412011-10-16 18:46:35 -07002040 const nsecs_t now = systemTime();
2041 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002042
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002043 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002044 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002045 continue;
2046 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002047 const auto displayId = display->getId();
2048 if (displayId >= 0) {
2049 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002050 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002051 display->onSwapBuffersCompleted();
2052 display->makeCurrent();
2053 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002054 // The layer buffer from the previous frame (if any) is released
2055 // by HWC only when the release fence from this frame (if any) is
2056 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002057 auto hwcLayer = layer->getHwcLayer(displayId);
2058 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002059
2060 // If the layer was client composited in the previous frame, we
2061 // need to merge with the previous client target acquire fence.
2062 // Since we do not track that, always merge with the current
2063 // client target acquire fence when it is available, even though
2064 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002065 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002066 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002067 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002068 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002069
David Sodmanb8af7922017-12-21 15:17:55 -08002070 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002071 }
Chia-I Wu83806892017-11-16 10:50:20 -08002072
2073 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002074 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002075 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002076 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002077 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002078 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002079 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002080 }
2081 }
2082
Dominik Laskowski7e045462018-05-30 13:02:02 -07002083 if (displayId >= 0) {
2084 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002085 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002086 }
2087
Mathias Agopiana44b0412011-10-16 18:46:35 -07002088 mLastSwapBufferTime = systemTime() - now;
2089 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002090
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002091 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002092 const auto display = getDefaultDisplayDeviceLocked();
2093 if (display && getHwComposer().isConnected(display->getId())) {
2094 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002095 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2096 logFrameStats();
2097 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002098 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002099}
2100
Mathias Agopian87baae12012-07-31 12:38:26 -07002101void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002102{
Mathias Agopian841cde52012-03-01 15:44:37 -08002103 ATRACE_CALL();
2104
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002105 // here we keep a copy of the drawing state (that is the state that's
2106 // going to be overwritten by handleTransactionLocked()) outside of
2107 // mStateLock so that the side-effects of the State assignment
2108 // don't happen with mStateLock held (which can cause deadlocks).
2109 State drawingState(mDrawingState);
2110
Mathias Agopianca4d3602011-05-19 15:38:14 -07002111 Mutex::Autolock _l(mStateLock);
2112 const nsecs_t now = systemTime();
2113 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002114
Mathias Agopianca4d3602011-05-19 15:38:14 -07002115 // Here we're guaranteed that some transaction flags are set
2116 // so we can call handleTransactionLocked() unconditionally.
2117 // We call getTransactionFlags(), which will also clear the flags,
2118 // with mStateLock held to guarantee that mCurrentState won't change
2119 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002120
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002121 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002122 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002123 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002124
Mathias Agopianca4d3602011-05-19 15:38:14 -07002125 mLastTransactionTime = systemTime() - now;
2126 mDebugInTransaction = 0;
2127 invalidateHwcGeometry();
2128 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002129}
2130
Dominik Laskowski7e045462018-05-30 13:02:02 -07002131DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002132 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002133 // Figure out whether the event is for the primary display or an
2134 // external display by matching the Hwc display id against one for a
2135 // connected display. If we did not find a match, we then check what
2136 // displays are not already connected to determine the type. If we don't
2137 // have a connected primary display, we assume the new display is meant to
2138 // be the primary display, and then if we don't have an external display,
2139 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002140 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2141 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002142 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002143 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002144 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002145 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002146 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002147 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002148 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002149 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002150 return DisplayDevice::DISPLAY_EXTERNAL;
2151 }
2152
2153 return DisplayDevice::DISPLAY_ID_INVALID;
2154}
2155
Lloyd Piqueba04e622017-12-14 17:11:26 -08002156void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2157 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002158 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002159 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002160 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002161 continue;
2162 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002163
2164 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2165 ALOGE("External displays are not supported by the vr hardware composer.");
2166 continue;
2167 }
2168
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002169 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002170 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002171 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002172 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002173 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002174
2175 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002176 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002177 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002178 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002179 DisplayDeviceState info;
2180 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002181 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2182 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002183 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002184 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002185 mInterceptor->saveDisplayCreation(info);
2186 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002187 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002188 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002189
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002190 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002191 if (idx >= 0) {
2192 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002193 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002194 mCurrentState.displays.removeItemsAt(idx);
2195 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002196 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002197 }
2198
2199 processDisplayChangesLocked();
2200 }
2201
2202 mPendingHotplugEvents.clear();
2203}
2204
Lloyd Pique99d3da52018-01-22 17:48:03 -08002205sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002206 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002207 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002208 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002209 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002210
Lloyd Pique99d3da52018-01-22 17:48:03 -08002211 if (hasWideColorDisplay) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002212 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002213 for (ColorMode colorMode : modes) {
2214 switch (colorMode) {
2215 case ColorMode::DISPLAY_P3:
2216 case ColorMode::ADOBE_RGB:
2217 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002218 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002219 break;
2220 default:
2221 break;
2222 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002223
Dominik Laskowski7e045462018-05-30 13:02:02 -07002224 std::vector<RenderIntent> renderIntents =
2225 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002226 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002227 }
2228 }
2229
Peiyong Lin62665892018-04-16 11:07:44 -07002230 HdrCapabilities hdrCapabilities;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002231 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002232
2233 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2234 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2235
2236 /*
2237 * Create our display's surface
2238 */
2239 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2240 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002241 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002242 renderSurface->setNativeWindow(nativeWindow.get());
2243 const int displayWidth = renderSurface->queryWidth();
2244 const int displayHeight = renderSurface->queryHeight();
2245
2246 // Make sure that composition can never be stalled by a virtual display
2247 // consumer that isn't processing buffers fast enough. We have to do this
2248 // in two places:
2249 // * Here, in case the display is composed entirely by HWC.
2250 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2251 // window's swap interval in eglMakeCurrent, so they'll override the
2252 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002253 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002254 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2255 }
2256
2257 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002258 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002259
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002260 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002261 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2262 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2263 displayHeight, hasWideColorGamut, hdrCapabilities,
2264 getHwComposer().getSupportedPerFrameMetadata(displayId),
2265 hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002266
2267 if (maxFrameBufferAcquiredBuffers >= 3) {
2268 nativeWindowSurface->preallocateBuffers();
2269 }
2270
2271 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002272 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2273 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002274 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002275 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002276 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002277 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002278 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002279 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002280 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002281 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002282 display->setLayerStack(state.layerStack);
2283 display->setProjection(state.orientation, state.viewport, state.frame);
2284 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002285
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002286 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002287}
2288
Lloyd Pique347200f2017-12-14 17:00:15 -08002289void SurfaceFlinger::processDisplayChangesLocked() {
2290 // here we take advantage of Vector's copy-on-write semantics to
2291 // improve performance by skipping the transaction entirely when
2292 // know that the lists are identical
2293 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2294 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2295 if (!curr.isIdenticalTo(draw)) {
2296 mVisibleRegionsDirty = true;
2297 const size_t cc = curr.size();
2298 size_t dc = draw.size();
2299
2300 // find the displays that were removed
2301 // (ie: in drawing state but not in current state)
2302 // also handle displays that changed
2303 // (ie: displays that are in both lists)
2304 for (size_t i = 0; i < dc;) {
2305 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2306 if (j < 0) {
2307 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002308 // Call makeCurrent() on the primary display so we can
2309 // be sure that nothing associated with this display
2310 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002311 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2312 defaultDisplay->makeCurrent();
2313 }
2314 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2315 display->disconnect(getHwComposer());
2316 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002317 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2318 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2319 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2320 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2321 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002322 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002323 } else {
2324 // this display is in both lists. see if something changed.
2325 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002326 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002327 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2328 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2329 if (state_binder != draw_binder) {
2330 // changing the surface is like destroying and
2331 // recreating the DisplayDevice, so we just remove it
2332 // from the drawing state, so that it get re-added
2333 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002334 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2335 display->disconnect(getHwComposer());
2336 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002337 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002338 mDrawingState.displays.removeItemsAt(i);
2339 dc--;
2340 // at this point we must loop to the next item
2341 continue;
2342 }
2343
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002344 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002345 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002346 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002347 }
2348 if ((state.orientation != draw[i].orientation) ||
2349 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002350 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002351 }
2352 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002353 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002354 }
2355 }
2356 }
2357 ++i;
2358 }
2359
2360 // find displays that were added
2361 // (ie: in current state but not in drawing state)
2362 for (size_t i = 0; i < cc; i++) {
2363 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2364 const DisplayDeviceState& state(curr[i]);
2365
2366 sp<DisplaySurface> dispSurface;
2367 sp<IGraphicBufferProducer> producer;
2368 sp<IGraphicBufferProducer> bqProducer;
2369 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002370 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002371
Dominik Laskowski7e045462018-05-30 13:02:02 -07002372 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002373 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002374 // Virtual displays without a surface are dormant:
2375 // they have external state (layer stack, projection,
2376 // etc.) but no internal state (i.e. a DisplayDevice).
2377 if (state.surface != nullptr) {
2378 // Allow VR composer to use virtual displays.
2379 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2380 int width = 0;
2381 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2382 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2383 int height = 0;
2384 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2385 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2386 int intFormat = 0;
2387 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2388 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002389 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002390
Dominik Laskowski7e045462018-05-30 13:02:02 -07002391 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2392 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002393 }
2394
2395 // TODO: Plumb requested format back up to consumer
2396
2397 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002398 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002399 bqProducer, bqConsumer,
2400 state.displayName);
2401
2402 dispSurface = vds;
2403 producer = vds;
2404 }
2405 } else {
2406 ALOGE_IF(state.surface != nullptr,
2407 "adding a supported display, but rendering "
2408 "surface is provided (%p), ignoring it",
2409 state.surface.get());
2410
Dominik Laskowski7e045462018-05-30 13:02:02 -07002411 displayId = state.type;
2412 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002413 producer = bqProducer;
2414 }
2415
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002416 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002417 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002418 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002419 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002420 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002421 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002422 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2423 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2424 true);
2425 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2426 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2427 true);
2428 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002429 }
2430 }
2431 }
2432 }
2433 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002434
2435 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002436}
2437
Mathias Agopian87baae12012-07-31 12:38:26 -07002438void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002439{
Dan Stoza7dde5992015-05-22 09:51:44 -07002440 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002441 mCurrentState.traverseInZOrder([](Layer* layer) {
2442 layer->notifyAvailableFrames();
2443 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002444
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445 /*
2446 * Traversal of the children
2447 * (perform the transaction for each of them if needed)
2448 */
2449
Mathias Agopian3559b072012-08-15 13:46:03 -07002450 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002451 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002452 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002453 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454
2455 const uint32_t flags = layer->doTransaction(0);
2456 if (flags & Layer::eVisibleRegion)
2457 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002458 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002459 }
2460
2461 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002462 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463 */
2464
Mathias Agopiane57f2922012-08-09 16:29:12 -07002465 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002466 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002467 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002468 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002469
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002470 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002471 // The transform hint might have changed for some layers
2472 // (either because a display has changed, or because a layer
2473 // as changed).
2474 //
2475 // Walk through all the layers in currentLayers,
2476 // and update their transform hint.
2477 //
2478 // If a layer is visible only on a single display, then that
2479 // display is used to calculate the hint, otherwise we use the
2480 // default display.
2481 //
2482 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2483 // the hint is set before we acquire a buffer from the surface texture.
2484 //
2485 // NOTE: layer transactions have taken place already, so we use their
2486 // drawing state. However, SurfaceFlinger's own transaction has not
2487 // happened yet, so we must use the current state layer list
2488 // (soon to become the drawing state list).
2489 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002490 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002491 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002492 bool first = true;
2493 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002494 // NOTE: we rely on the fact that layers are sorted by
2495 // layerStack first (so we don't have to traverse the list
2496 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002497 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002498 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002499 currentlayerStack = layerStack;
2500 // figure out if this layerstack is mirrored
2501 // (more than one display) if so, pick the default display,
2502 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002503 hintDisplay = nullptr;
2504 for (const auto& [token, display] : mDisplays) {
2505 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2506 if (hintDisplay) {
2507 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002508 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002509 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002510 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002511 }
2512 }
2513 }
2514 }
Chet Haase91d25932013-04-11 15:24:55 -07002515
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002516 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002517 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2518 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002519
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002520 // could be null when this layer is using a layerStack
2521 // that is not visible on any display. Also can occur at
2522 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002523 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002524 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002525
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002526 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002527 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002528 if (hintDisplay) {
2529 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002530 }
Robert Carr2047fae2016-11-28 14:09:09 -08002531
2532 first = false;
2533 });
Mathias Agopian84300952012-11-21 16:02:13 -08002534 }
2535
2536
Mathias Agopian3559b072012-08-15 13:46:03 -07002537 /*
2538 * Perform our own transaction if needed
2539 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002540
2541 if (mLayersAdded) {
2542 mLayersAdded = false;
2543 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002544 mVisibleRegionsDirty = true;
2545 }
2546
2547 // some layers might have been removed, so
2548 // we need to update the regions they're exposing.
2549 if (mLayersRemoved) {
2550 mLayersRemoved = false;
2551 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002552 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002553 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002554 // this layer is not visible anymore
2555 // TODO: we could traverse the tree from front to back and
2556 // compute the actual visible region
2557 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002558 Region visibleReg;
2559 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002560 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002561 }
Robert Carr2047fae2016-11-28 14:09:09 -08002562 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002563 }
2564
2565 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002566
2567 updateCursorAsync();
2568}
2569
2570void SurfaceFlinger::updateCursorAsync()
2571{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002572 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002573 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002574 continue;
2575 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002576
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002577 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2578 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002579 }
2580 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002581}
2582
2583void SurfaceFlinger::commitTransaction()
2584{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002585 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002586 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002587 for (const auto& l : mLayersPendingRemoval) {
2588 recordBufferingStats(l->getName().string(),
2589 l->getOccupancyHistory(true));
2590 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002591 }
2592 mLayersPendingRemoval.clear();
2593 }
2594
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002595 // If this transaction is part of a window animation then the next frame
2596 // we composite should be considered an animation as well.
2597 mAnimCompositionPending = mAnimTransactionPending;
2598
Mathias Agopian4fec8732012-06-29 14:12:52 -07002599 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002600 // clear the "changed" flags in current state
2601 mCurrentState.colorMatrixChanged = false;
2602
Robert Carr1f0a16a2016-10-24 16:27:39 -07002603 mDrawingState.traverseInZOrder([](Layer* layer) {
2604 layer->commitChildList();
2605 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002606 mTransactionPending = false;
2607 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002608 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002609}
2610
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002611void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2612 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002613 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002614 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002615
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002616 Region aboveOpaqueLayers;
2617 Region aboveCoveredLayers;
2618 Region dirty;
2619
Mathias Agopian87baae12012-07-31 12:38:26 -07002620 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621
Robert Carr2047fae2016-11-28 14:09:09 -08002622 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002623 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002624 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625
Jesse Hall01e29052013-02-19 16:13:35 -08002626 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002627 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002628 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002629 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002630
Mathias Agopianab028732010-03-16 16:41:46 -07002631 /*
2632 * opaqueRegion: area of a surface that is fully opaque.
2633 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002635
2636 /*
2637 * visibleRegion: area of a surface that is visible on screen
2638 * and not fully transparent. This is essentially the layer's
2639 * footprint minus the opaque regions above it.
2640 * Areas covered by a translucent surface are considered visible.
2641 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002643
2644 /*
2645 * coveredRegion: area of a surface that is covered by all
2646 * visible regions above it (which includes the translucent areas).
2647 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002649
Jesse Halla8026d22012-09-25 13:25:04 -07002650 /*
2651 * transparentRegion: area of a surface that is hinted to be completely
2652 * transparent. This is only used to tell when the layer has no visible
2653 * non-transparent regions and can be removed from the layer list. It
2654 * does not affect the visibleRegion of this layer or any layers
2655 * beneath it. The hint may not be correct if apps don't respect the
2656 * SurfaceView restrictions (which, sadly, some don't).
2657 */
2658 Region transparentRegion;
2659
Mathias Agopianab028732010-03-16 16:41:46 -07002660
2661 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002662 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002663 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002664 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002666 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002667 if (!visibleRegion.isEmpty()) {
2668 // Remove the transparent area from the visible region
2669 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002670 if (tr.preserveRects()) {
2671 // transform the transparent region
2672 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002673 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002674 // transformation too complex, can't do the
2675 // transparent region optimization.
2676 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002677 }
Mathias Agopianab028732010-03-16 16:41:46 -07002678 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002679
Mathias Agopianab028732010-03-16 16:41:46 -07002680 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002681 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002682 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002683 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2684 // the opaque region is the layer's footprint
2685 opaqueRegion = visibleRegion;
2686 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687 }
2688 }
2689
Robert Carre5f4f692018-01-12 13:12:28 -08002690 if (visibleRegion.isEmpty()) {
2691 layer->clearVisibilityRegions();
2692 return;
2693 }
2694
Mathias Agopianab028732010-03-16 16:41:46 -07002695 // Clip the covered region to the visible region
2696 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2697
2698 // Update aboveCoveredLayers for next (lower) layer
2699 aboveCoveredLayers.orSelf(visibleRegion);
2700
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002701 // subtract the opaque region covered by the layers above us
2702 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002703
2704 // compute this layer's dirty region
2705 if (layer->contentDirty) {
2706 // we need to invalidate the whole region
2707 dirty = visibleRegion;
2708 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002709 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002710 layer->contentDirty = false;
2711 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002712 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002713 * the exposed region consists of two components:
2714 * 1) what's VISIBLE now and was COVERED before
2715 * 2) what's EXPOSED now less what was EXPOSED before
2716 *
2717 * note that (1) is conservative, we start with the whole
2718 * visible region but only keep what used to be covered by
2719 * something -- which mean it may have been exposed.
2720 *
2721 * (2) handles areas that were not covered by anything but got
2722 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002723 */
Mathias Agopianab028732010-03-16 16:41:46 -07002724 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002725 const Region oldVisibleRegion = layer->visibleRegion;
2726 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002727 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2728 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002729 }
2730 dirty.subtractSelf(aboveOpaqueLayers);
2731
2732 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002733 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002734
Mathias Agopianab028732010-03-16 16:41:46 -07002735 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002737
Jesse Halla8026d22012-09-25 13:25:04 -07002738 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739 layer->setVisibleRegion(visibleRegion);
2740 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002741 layer->setVisibleNonTransparentRegion(
2742 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002743 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744
Mathias Agopian87baae12012-07-31 12:38:26 -07002745 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746}
2747
Chia-I Wuab0c3192017-08-01 11:29:00 -07002748void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002749 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002750 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2751 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002752 }
2753 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002754}
2755
Dan Stoza6b9454d2014-11-07 16:00:59 -08002756bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002757{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002758 ALOGV("handlePageFlip");
2759
Brian Andersond6927fb2016-07-23 23:37:30 -07002760 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761
Mathias Agopian4fec8732012-06-29 14:12:52 -07002762 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002763 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002764 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002765
2766 // Store the set of layers that need updates. This set must not change as
2767 // buffers are being latched, as this could result in a deadlock.
2768 // Example: Two producers share the same command stream and:
2769 // 1.) Layer 0 is latched
2770 // 2.) Layer 0 gets a new frame
2771 // 2.) Layer 1 gets a new frame
2772 // 3.) Layer 1 is latched.
2773 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2774 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002775 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002776 if (layer->hasQueuedFrame()) {
2777 frameQueued = true;
2778 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002779 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002780 } else {
2781 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002782 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002783 } else {
2784 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002785 }
Robert Carr2047fae2016-11-28 14:09:09 -08002786 });
2787
Dan Stoza9e56aa02015-11-02 13:00:03 -08002788 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002789 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002790 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002791 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002792 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002793 newDataLatched = true;
2794 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002795 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002796
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002797 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002798
2799 // If we will need to wake up at some time in the future to deal with a
2800 // queued frame that shouldn't be displayed during this vsync period, wake
2801 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002802 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002803 signalLayerUpdate();
2804 }
2805
2806 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002807 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002808}
2809
Mathias Agopianad456f92011-01-13 17:53:01 -08002810void SurfaceFlinger::invalidateHwcGeometry()
2811{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002812 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002813}
2814
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002815void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2816 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002817 // We only need to actually compose the display if:
2818 // 1) It is being handled by hardware composer, which may need this to
2819 // keep its virtual display state machine in sync, or
2820 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002821 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002822 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002823 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002824 return;
2825 }
2826
Dan Stoza9e56aa02015-11-02 13:00:03 -08002827 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002828 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002829
2830 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002831 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832}
2833
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002834bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002835 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002836
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002837 const Region bounds(display->bounds());
2838 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002839 const auto displayId = display->getId();
2840 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002841 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002842
Chia-I Wu8e50e692018-05-04 10:12:37 -07002843 bool applyColorMatrix = false;
Peiyong Lin00f9c022018-05-09 15:35:33 -07002844 bool needsLegacyColorMatrix = false;
2845 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002846
Dan Stoza9e56aa02015-11-02 13:00:03 -08002847 if (hasClientComposition) {
2848 ALOGV("hasClientComposition");
2849
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002850 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002851 if (display->hasWideColorGamut()) {
2852 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002853 }
2854 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002855 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002856 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002857
Dominik Laskowski7e045462018-05-30 13:02:02 -07002858 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002859 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2860 HWC2::Capability::SkipClientColorTransform);
2861
2862 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2863 if (applyColorMatrix) {
Peiyong Lin00f9c022018-05-09 15:35:33 -07002864 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002865 }
2866
Chia-I Wubbb44462018-05-21 15:33:27 -07002867 needsLegacyColorMatrix =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002868 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2869 outputDataspace != Dataspace::UNKNOWN && outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002870
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002871 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002872 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002873 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002874 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002875
2876 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002877 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2878 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2879 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002880 }
2881 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002882 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002883
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002884 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002885 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002886 // when using overlays, we assume a fully transparent framebuffer
2887 // NOTE: we could reduce how much we need to clear, for instance
2888 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002889 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002890 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002891 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002892 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002893 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002894 // we're left with the letterbox region
2895 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002896 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002897
2898 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002899 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002900
Mathias Agopianb9494d52012-04-18 02:28:45 -07002901 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002902 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002903 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002904 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002905 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002906 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002907
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002908 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002909 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002910 // scissor on the main display. It should never be needed
2911 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002912 const Rect& bounds = display->getBounds();
2913 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002914 if (scissor != bounds) {
2915 // scissor doesn't match the screen's dimensions, so we
2916 // need to clear everything outside of it and enable
2917 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002918
Mathias Agopianf45c5102012-10-24 16:29:17 -07002919 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002920 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002921 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002922 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002923 }
2924 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002925 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002926
Mathias Agopian85d751c2012-08-29 16:59:24 -07002927 /*
2928 * and then, render the layers targeted at the framebuffer
2929 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002930
Dan Stoza9e56aa02015-11-02 13:00:03 -08002931 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002932 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002933 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002934 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002935 const Region clip(bounds.intersect(
2936 displayTransform.transform(layer->visibleRegion)));
2937 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002938 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002939 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002940 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002941 case HWC2::Composition::Cursor:
2942 case HWC2::Composition::Device:
2943 case HWC2::Composition::Sideband:
2944 case HWC2::Composition::SolidColor: {
2945 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002946 if (layer->getClearClientTarget(displayId) && !firstLayer &&
2947 layer->isOpaque(state) && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002948 // never clear the very first layer since we're
2949 // guaranteed the FB is already cleared
2950 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002951 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002952 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002953 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002954 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002955 // switch color matrices lazily
Peiyong Lin00f9c022018-05-09 15:35:33 -07002956 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
2957 if (!legacyColorMatrixApplied) {
2958 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
2959 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002960 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07002961 } else if (legacyColorMatrixApplied) {
2962 getRenderEngine().setSaturationMatrix(mat4());
2963 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002964 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07002965
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002966 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002967 break;
2968 }
2969 default:
2970 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002971 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002972 } else {
2973 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002974 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002975 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002976 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002977
Peiyong Lin00f9c022018-05-09 15:35:33 -07002978 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002979 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002980 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07002981 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
2982 getRenderEngine().setSaturationMatrix(mat4());
2983 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002984
Mathias Agopianf45c5102012-10-24 16:29:17 -07002985 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002986 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002987 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002988}
2989
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002990void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2991 const Region& region) const {
2992 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002993 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002994 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002995}
2996
Dan Stoza7d89d062015-04-30 13:29:25 -07002997status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002998 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002999 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003000 const sp<Layer>& lbc,
3001 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003002{
Dan Stoza7d89d062015-04-30 13:29:25 -07003003 // add this layer to the current state list
3004 {
3005 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003006 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003007 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3008 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003009 return NO_MEMORY;
3010 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003011 if (parent == nullptr) {
3012 mCurrentState.layersSortedByZ.add(lbc);
3013 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003014 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003015 ALOGE("addClientLayer called with a removed parent");
3016 return NAME_NOT_FOUND;
3017 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003018 parent->addChild(lbc);
3019 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003020
Yiwei Zhang243b3782018-05-15 17:40:04 -07003021 if (gbc != nullptr) {
3022 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3023 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3024 mMaxGraphicBufferProducerListSize,
3025 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3026 mGraphicBufferProducerList.size(),
3027 mMaxGraphicBufferProducerListSize, mNumLayers);
3028 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003029 mLayersAdded = true;
3030 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003031 }
3032
Mathias Agopian96f08192010-06-02 23:28:45 -07003033 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003034 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003035
Dan Stoza7d89d062015-04-30 13:29:25 -07003036 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003037}
3038
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003039status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003040 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003041 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3042}
Robert Carr7f9b8992017-03-10 11:08:39 -08003043
chaviwca27f252018-02-06 16:46:39 -08003044status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3045 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003046 if (layer->isPendingRemoval()) {
3047 return NO_ERROR;
3048 }
3049
Robert Carr1f0a16a2016-10-24 16:27:39 -07003050 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003051 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003052 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003053 if (topLevelOnly) {
3054 return NO_ERROR;
3055 }
3056
Chia-I Wu98f1c102017-05-30 14:54:08 -07003057 sp<Layer> ancestor = p;
3058 while (ancestor->getParent() != nullptr) {
3059 ancestor = ancestor->getParent();
3060 }
3061 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3062 ALOGE("removeLayer called with a layer whose parent has been removed");
3063 return NAME_NOT_FOUND;
3064 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003065
3066 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003067 } else {
3068 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003069 }
3070
Robert Carr136e2f62017-02-08 17:54:29 -08003071 // As a matter of normal operation, the LayerCleaner will produce a second
3072 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3073 // so we will succeed in promoting it, but it's already been removed
3074 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3075 // otherwise something has gone wrong and we are leaking the layer.
3076 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003077 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3078 layer->getName().string(),
3079 (p != nullptr) ? p->getName().string() : "no-parent");
3080 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003081 } else if (index < 0) {
3082 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003083 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003084
Chia-I Wuc6657022017-08-15 11:18:17 -07003085 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003086 mLayersPendingRemoval.add(layer);
3087 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003088 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003089 setTransactionFlags(eTransactionNeeded);
3090 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091}
3092
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003093uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003094 return android_atomic_release_load(&mTransactionFlags);
3095}
3096
Mathias Agopian3f844832013-08-07 21:24:32 -07003097uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3099}
3100
Mathias Agopian3f844832013-08-07 21:24:32 -07003101uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003102 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3103}
3104
3105uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3106 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003107 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003108 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003109 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003110 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111 }
3112 return old;
3113}
3114
chaviwca27f252018-02-06 16:46:39 -08003115bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3116 for (const ComposerState& state : states) {
3117 // Here we need to check that the interface we're given is indeed
3118 // one of our own. A malicious client could give us a nullptr
3119 // IInterface, or one of its own or even one of our own but a
3120 // different type. All these situations would cause us to crash.
3121 if (state.client == nullptr) {
3122 return true;
3123 }
3124
3125 sp<IBinder> binder = IInterface::asBinder(state.client);
3126 if (binder == nullptr) {
3127 return true;
3128 }
3129
3130 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3131 return true;
3132 }
3133 }
3134 return false;
3135}
3136
Mathias Agopian8b33f032012-07-24 20:43:54 -07003137void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003138 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003139 const Vector<DisplayState>& displays,
3140 uint32_t flags)
3141{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003142 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003143 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003144 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003145
chaviwca27f252018-02-06 16:46:39 -08003146 if (containsAnyInvalidClientState(states)) {
3147 return;
3148 }
3149
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003150 if (flags & eAnimation) {
3151 // For window updates that are part of an animation we must wait for
3152 // previous animation "frames" to be handled.
3153 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003154 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003155 if (CC_UNLIKELY(err != NO_ERROR)) {
3156 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003157 // caller after a few seconds.
3158 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3159 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003160 mAnimTransactionPending = false;
3161 break;
3162 }
3163 }
3164 }
3165
chaviwca27f252018-02-06 16:46:39 -08003166 for (const DisplayState& display : displays) {
3167 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003168 }
3169
chaviwca27f252018-02-06 16:46:39 -08003170 for (const ComposerState& state : states) {
3171 transactionFlags |= setClientStateLocked(state);
3172 }
3173
3174 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3175 // as destroyed should only occur after setting all other states. This is to allow for a
3176 // child re-parent to happen before marking its original parent as destroyed (which would
3177 // then mark the child as destroyed).
3178 for (const ComposerState& state : states) {
3179 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003180 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003181
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003182 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3183 // anyway. This can be used as a flush mechanism for previous async transactions.
3184 // Empty animation transaction can be used to simulate back-pressure, so also force a
3185 // transaction for empty animation transactions.
3186 if (transactionFlags == 0 &&
3187 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003188 transactionFlags = eTransactionNeeded;
3189 }
3190
Mathias Agopian386aa982011-11-07 21:58:03 -08003191 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003192 if (mInterceptor->isEnabled()) {
3193 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003194 }
Irvel468051e2016-06-13 16:44:44 -07003195
Mathias Agopian386aa982011-11-07 21:58:03 -08003196 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003197 const auto start = (flags & eEarlyWakeup)
3198 ? VSyncModulator::TransactionStart::EARLY
3199 : VSyncModulator::TransactionStart::NORMAL;
3200 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003201
3202 // if this is a synchronous transaction, wait for it to take effect
3203 // before returning.
3204 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003205 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003206 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003207 if (flags & eAnimation) {
3208 mAnimTransactionPending = true;
3209 }
3210 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003211 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3212 if (CC_UNLIKELY(err != NO_ERROR)) {
3213 // just in case something goes wrong in SF, return to the
3214 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003215 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3216 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003217 break;
3218 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003219 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003220 }
3221}
3222
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003223uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3224 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3225 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003226
Mathias Agopiane57f2922012-08-09 16:29:12 -07003227 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003228 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3229
3230 const uint32_t what = s.what;
3231 if (what & DisplayState::eSurfaceChanged) {
3232 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3233 state.surface = s.surface;
3234 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003235 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003236 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003237 if (what & DisplayState::eLayerStackChanged) {
3238 if (state.layerStack != s.layerStack) {
3239 state.layerStack = s.layerStack;
3240 flags |= eDisplayTransactionNeeded;
3241 }
3242 }
3243 if (what & DisplayState::eDisplayProjectionChanged) {
3244 if (state.orientation != s.orientation) {
3245 state.orientation = s.orientation;
3246 flags |= eDisplayTransactionNeeded;
3247 }
3248 if (state.frame != s.frame) {
3249 state.frame = s.frame;
3250 flags |= eDisplayTransactionNeeded;
3251 }
3252 if (state.viewport != s.viewport) {
3253 state.viewport = s.viewport;
3254 flags |= eDisplayTransactionNeeded;
3255 }
3256 }
3257 if (what & DisplayState::eDisplaySizeChanged) {
3258 if (state.width != s.width) {
3259 state.width = s.width;
3260 flags |= eDisplayTransactionNeeded;
3261 }
3262 if (state.height != s.height) {
3263 state.height = s.height;
3264 flags |= eDisplayTransactionNeeded;
3265 }
3266 }
3267
Mathias Agopiane57f2922012-08-09 16:29:12 -07003268 return flags;
3269}
3270
chaviwca27f252018-02-06 16:46:39 -08003271uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3272 const layer_state_t& s = composerState.state;
3273 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3274
Mathias Agopian13127d82013-03-05 17:47:11 -08003275 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003276 if (layer == nullptr) {
3277 return 0;
3278 }
3279
3280 if (layer->isPendingRemoval()) {
3281 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3282 return 0;
3283 }
3284
3285 uint32_t flags = 0;
3286
3287 const uint32_t what = s.what;
3288 bool geometryAppliesWithResize =
3289 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003290
3291 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3292 // pending state will also be deferred.
3293 if (what & layer_state_t::eDeferTransaction) {
3294 layer->pushPendingState();
3295 }
3296
chaviw8b3871a2017-11-01 17:41:01 -07003297 if (what & layer_state_t::ePositionChanged) {
3298 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3299 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003300 }
chaviw8b3871a2017-11-01 17:41:01 -07003301 }
3302 if (what & layer_state_t::eLayerChanged) {
3303 // NOTE: index needs to be calculated before we update the state
3304 const auto& p = layer->getParent();
3305 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003306 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003307 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003308 mCurrentState.layersSortedByZ.removeAt(idx);
3309 mCurrentState.layersSortedByZ.add(layer);
3310 // we need traversal (state changed)
3311 // AND transaction (list changed)
3312 flags |= eTransactionNeeded|eTraversalNeeded;
3313 }
chaviw8b3871a2017-11-01 17:41:01 -07003314 } else {
3315 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003316 flags |= eTransactionNeeded|eTraversalNeeded;
3317 }
3318 }
chaviw8b3871a2017-11-01 17:41:01 -07003319 }
3320 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003321 // NOTE: index needs to be calculated before we update the state
3322 const auto& p = layer->getParent();
3323 if (p == nullptr) {
3324 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3325 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3326 mCurrentState.layersSortedByZ.removeAt(idx);
3327 mCurrentState.layersSortedByZ.add(layer);
3328 // we need traversal (state changed)
3329 // AND transaction (list changed)
3330 flags |= eTransactionNeeded|eTraversalNeeded;
3331 }
3332 } else {
3333 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3334 flags |= eTransactionNeeded|eTraversalNeeded;
3335 }
chaviw8b3871a2017-11-01 17:41:01 -07003336 }
3337 }
3338 if (what & layer_state_t::eSizeChanged) {
3339 if (layer->setSize(s.w, s.h)) {
3340 flags |= eTraversalNeeded;
3341 }
3342 }
3343 if (what & layer_state_t::eAlphaChanged) {
3344 if (layer->setAlpha(s.alpha))
3345 flags |= eTraversalNeeded;
3346 }
3347 if (what & layer_state_t::eColorChanged) {
3348 if (layer->setColor(s.color))
3349 flags |= eTraversalNeeded;
3350 }
3351 if (what & layer_state_t::eMatrixChanged) {
3352 if (layer->setMatrix(s.matrix))
3353 flags |= eTraversalNeeded;
3354 }
3355 if (what & layer_state_t::eTransparentRegionChanged) {
3356 if (layer->setTransparentRegionHint(s.transparentRegion))
3357 flags |= eTraversalNeeded;
3358 }
3359 if (what & layer_state_t::eFlagsChanged) {
3360 if (layer->setFlags(s.flags, s.mask))
3361 flags |= eTraversalNeeded;
3362 }
3363 if (what & layer_state_t::eCropChanged) {
3364 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3365 flags |= eTraversalNeeded;
3366 }
3367 if (what & layer_state_t::eFinalCropChanged) {
3368 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3369 flags |= eTraversalNeeded;
3370 }
3371 if (what & layer_state_t::eLayerStackChanged) {
3372 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3373 // We only allow setting layer stacks for top level layers,
3374 // everything else inherits layer stack from its parent.
3375 if (layer->hasParent()) {
3376 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3377 layer->getName().string());
3378 } else if (idx < 0) {
3379 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3380 "that also does not appear in the top level layer list. Something"
3381 " has gone wrong.", layer->getName().string());
3382 } else if (layer->setLayerStack(s.layerStack)) {
3383 mCurrentState.layersSortedByZ.removeAt(idx);
3384 mCurrentState.layersSortedByZ.add(layer);
3385 // we need traversal (state changed)
3386 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003387 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003388 }
3389 }
3390 if (what & layer_state_t::eDeferTransaction) {
3391 if (s.barrierHandle != nullptr) {
3392 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3393 } else if (s.barrierGbp != nullptr) {
3394 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3395 if (authenticateSurfaceTextureLocked(gbp)) {
3396 const auto& otherLayer =
3397 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3398 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3399 } else {
3400 ALOGE("Attempt to defer transaction to to an"
3401 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003402 }
3403 }
chaviw8b3871a2017-11-01 17:41:01 -07003404 // We don't trigger a traversal here because if no other state is
3405 // changed, we don't want this to cause any more work
3406 }
3407 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003408 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003409 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003410 if (!hadParent) {
3411 mCurrentState.layersSortedByZ.remove(layer);
3412 }
chaviw8b3871a2017-11-01 17:41:01 -07003413 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003414 }
chaviw8b3871a2017-11-01 17:41:01 -07003415 }
3416 if (what & layer_state_t::eReparentChildren) {
3417 if (layer->reparentChildren(s.reparentHandle)) {
3418 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003419 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003420 }
chaviw8b3871a2017-11-01 17:41:01 -07003421 if (what & layer_state_t::eDetachChildren) {
3422 layer->detachChildren();
3423 }
3424 if (what & layer_state_t::eOverrideScalingModeChanged) {
3425 layer->setOverrideScalingMode(s.overrideScalingMode);
3426 // We don't trigger a traversal here because if no other state is
3427 // changed, we don't want this to cause any more work
3428 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003429 return flags;
3430}
3431
chaviwca27f252018-02-06 16:46:39 -08003432void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3433 const layer_state_t& state = composerState.state;
3434 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3435
3436 sp<Layer> layer(client->getLayerUser(state.surface));
3437 if (layer == nullptr) {
3438 return;
3439 }
3440
3441 if (layer->isPendingRemoval()) {
3442 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3443 return;
3444 }
3445
3446 if (state.what & layer_state_t::eDestroySurface) {
3447 removeLayerLocked(mStateLock, layer);
3448 }
3449}
3450
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003451status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003452 const String8& name,
3453 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003454 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003455 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003456 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003457{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003458 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003459 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003460 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003461 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003462 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003463
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003464 status_t result = NO_ERROR;
3465
3466 sp<Layer> layer;
3467
Cody Northropbc755282017-03-31 12:00:08 -06003468 String8 uniqueName = getUniqueLayerName(name);
3469
Mathias Agopian3165cc22012-08-08 19:42:09 -07003470 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3471 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003472 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003473 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003474 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003475
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003476 break;
chaviw13fdc492017-06-27 12:40:18 -07003477 case ISurfaceComposerClient::eFXSurfaceColor:
3478 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003479 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003480 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003481 break;
3482 default:
3483 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003484 break;
3485 }
3486
Dan Stoza7d89d062015-04-30 13:29:25 -07003487 if (result != NO_ERROR) {
3488 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003489 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003490
Chia-I Wuab0c3192017-08-01 11:29:00 -07003491 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3492 // TODO b/64227542
3493 if (windowType == 441731) {
3494 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3495 layer->setPrimaryDisplayOnly();
3496 }
3497
Albert Chaulk479c60c2017-01-27 14:21:34 -05003498 layer->setInfo(windowType, ownerUid);
3499
Robert Carr1f0a16a2016-10-24 16:27:39 -07003500 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003501 if (result != NO_ERROR) {
3502 return result;
3503 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003504 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003505
3506 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003507 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003508}
3509
Cody Northropbc755282017-03-31 12:00:08 -06003510String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3511{
3512 bool matchFound = true;
3513 uint32_t dupeCounter = 0;
3514
3515 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3516 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3517
3518 // Loop over layers until we're sure there is no matching name
3519 while (matchFound) {
3520 matchFound = false;
3521 mDrawingState.traverseInZOrder([&](Layer* layer) {
3522 if (layer->getName() == uniqueName) {
3523 matchFound = true;
3524 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3525 }
3526 });
3527 }
3528
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003529 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3530 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003531
3532 return uniqueName;
3533}
3534
David Sodman0c69cad2017-08-21 12:12:51 -07003535status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003536 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3537 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003538{
3539 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003540 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003541 case PIXEL_FORMAT_TRANSPARENT:
3542 case PIXEL_FORMAT_TRANSLUCENT:
3543 format = PIXEL_FORMAT_RGBA_8888;
3544 break;
3545 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003546 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003547 break;
3548 }
3549
David Sodman0c69cad2017-08-21 12:12:51 -07003550 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3551 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003552 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003553 *handle = layer->getHandle();
3554 *gbp = layer->getProducer();
3555 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003556 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003557
David Sodman0c69cad2017-08-21 12:12:51 -07003558 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003559 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003560}
3561
chaviw13fdc492017-06-27 12:40:18 -07003562status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003563 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003564 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003565{
chaviw13fdc492017-06-27 12:40:18 -07003566 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003567 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003568 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003569}
3570
Mathias Agopianac9fa422013-02-11 16:40:36 -08003571status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572{
Robert Carr9524cb32017-02-13 11:32:32 -08003573 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003574 status_t err = NO_ERROR;
3575 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003576 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003577 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003578 err = removeLayer(l);
3579 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3580 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003581 }
3582 return err;
3583}
3584
Mathias Agopian13127d82013-03-05 17:47:11 -08003585status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003586{
Mathias Agopian67106042013-03-14 19:18:13 -07003587 // called by ~LayerCleaner() when all references to the IBinder (handle)
3588 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003589 sp<Layer> l = layer.promote();
3590 if (l == nullptr) {
3591 // The layer has already been removed, carry on
3592 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003593 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003594 // If we have a parent, then we can continue to live as long as it does.
3595 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003596}
3597
Mathias Agopianb60314a2012-04-10 22:09:54 -07003598// ---------------------------------------------------------------------------
3599
Andy McFadden13a082e2012-08-24 10:16:42 -07003600void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003601 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3602 if (!displayToken) return;
3603
Jesse Hall01e29052013-02-19 16:13:35 -08003604 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003605 Vector<ComposerState> state;
3606 Vector<DisplayState> displays;
3607 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003608 d.what = DisplayState::eDisplayProjectionChanged |
3609 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003610 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003611 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003612 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003613 d.frame.makeInvalid();
3614 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003615 d.width = 0;
3616 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003617 displays.add(d);
3618 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003619
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003620 const auto display = getDisplayDevice(displayToken);
3621 if (!display) return;
3622
3623 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3624
3625 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003626 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003627 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003628
Brian Andersond0010582017-03-07 13:20:31 -08003629 // Use phase of 0 since phase is not known.
3630 // Use latency of 0, which will snap to the ideal latency.
3631 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003632}
3633
3634void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003635 // Async since we may be called from the main thread.
3636 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003637}
3638
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003639void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3640 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003641 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003642 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003643
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003644 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003645 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003646 return;
3647 }
3648
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003649 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003650 ALOGW("Trying to set power mode for virtual display");
3651 return;
3652 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003653
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003654 display->setPowerMode(mode);
3655
Lloyd Pique4dccc412018-01-22 17:21:36 -08003656 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003657 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003658 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003659 if (idx < 0) {
3660 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3661 return;
3662 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003663 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003664 }
3665
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003666 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003667 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003668 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003669 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003670 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003671 // FIXME: eventthread only knows about the main display right now
3672 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003673 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003674 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003675
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003676 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003677 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003678 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003679
3680 struct sched_param param = {0};
3681 param.sched_priority = 1;
3682 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3683 ALOGW("Couldn't set SCHED_FIFO on display on");
3684 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003685 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003686 // Turn off the display
3687 struct sched_param param = {0};
3688 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3689 ALOGW("Couldn't set SCHED_OTHER on display off");
3690 }
3691
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003692 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003693 disableHardwareVsync(true); // also cancels any in-progress resync
3694
Mathias Agopiancde87a32012-09-13 14:09:01 -07003695 // FIXME: eventthread only knows about the main display right now
3696 mEventThread->onScreenReleased();
3697 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003698
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003699 getHwComposer().setPowerMode(type, mode);
3700 mVisibleRegionsDirty = true;
3701 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003702 } else if (mode == HWC_POWER_MODE_DOZE ||
3703 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003704 // Update display while dozing
3705 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003706 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003707 // FIXME: eventthread only knows about the main display right now
3708 mEventThread->onScreenAcquired();
3709 resyncToHardwareVsync(true);
3710 }
3711 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3712 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003713 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003714 disableHardwareVsync(true); // also cancels any in-progress resync
3715 // FIXME: eventthread only knows about the main display right now
3716 mEventThread->onScreenReleased();
3717 }
3718 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003719 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003720 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003721 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003722 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003723
3724 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003725}
3726
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003727void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003728 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003729 const auto display = getDisplayDevice(displayToken);
3730 if (!display) {
3731 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3732 displayToken.get());
3733 } else if (display->isVirtual()) {
3734 ALOGW("Attempt to set power mode %d for virtual display", mode);
3735 } else {
3736 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003737 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003738 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003739}
3740
3741// ---------------------------------------------------------------------------
3742
Lloyd Pique755e3192018-01-31 16:46:15 -08003743status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3744 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003745 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003746
Mathias Agopianbd115332013-04-18 16:41:04 -07003747 IPCThreadState* ipc = IPCThreadState::self();
3748 const int pid = ipc->getCallingPid();
3749 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003750
Mathias Agopianbd115332013-04-18 16:41:04 -07003751 if ((uid != AID_SHELL) &&
3752 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003753 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003754 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003755 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003756 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003757 // (this would indicate SF is stuck, but we want to be able to
3758 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003759 status_t err = mStateLock.timedLock(s2ns(1));
3760 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003761 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003762 result.appendFormat(
3763 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3764 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003765 }
3766
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003767 bool dumpAll = true;
3768 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003769 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003770
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003771 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003772 if ((index < numArgs) &&
3773 (args[index] == String16("--list"))) {
3774 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003775 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003776 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003777 }
3778
3779 if ((index < numArgs) &&
3780 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003781 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003782 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003783 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003784 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003785
3786 if ((index < numArgs) &&
3787 (args[index] == String16("--latency-clear"))) {
3788 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003789 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003790 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003791 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003792
3793 if ((index < numArgs) &&
3794 (args[index] == String16("--dispsync"))) {
3795 index++;
3796 mPrimaryDispSync.dump(result);
3797 dumpAll = false;
3798 }
Dan Stozab90cf072015-03-05 11:05:59 -08003799
3800 if ((index < numArgs) &&
3801 (args[index] == String16("--static-screen"))) {
3802 index++;
3803 dumpStaticScreenStats(result);
3804 dumpAll = false;
3805 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003806
3807 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003808 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003809 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003810 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003811 dumpAll = false;
3812 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003813
3814 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3815 index++;
3816 dumpWideColorInfo(result);
3817 dumpAll = false;
3818 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003819
3820 if ((index < numArgs) &&
3821 (args[index] == String16("--enable-layer-stats"))) {
3822 index++;
3823 mLayerStats.enable();
3824 dumpAll = false;
3825 }
3826
3827 if ((index < numArgs) &&
3828 (args[index] == String16("--disable-layer-stats"))) {
3829 index++;
3830 mLayerStats.disable();
3831 dumpAll = false;
3832 }
3833
3834 if ((index < numArgs) &&
3835 (args[index] == String16("--clear-layer-stats"))) {
3836 index++;
3837 mLayerStats.clear();
3838 dumpAll = false;
3839 }
3840
3841 if ((index < numArgs) &&
3842 (args[index] == String16("--dump-layer-stats"))) {
3843 index++;
3844 mLayerStats.dump(result);
3845 dumpAll = false;
3846 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003847
3848 if ((index < numArgs) &&
3849 (args[index] == String16("--display-identification"))) {
3850 index++;
3851 dumpDisplayIdentificationData(result);
3852 dumpAll = false;
3853 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003854
3855 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3856 index++;
3857 mTimeStats.parseArgs(asProto, args, index, result);
3858 dumpAll = false;
3859 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003860 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003861
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003862 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003863 if (asProto) {
3864 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3865 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3866 } else {
3867 dumpAllLocked(args, index, result);
3868 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003869 }
3870
Mathias Agopian9795c422009-08-26 16:36:26 -07003871 if (locked) {
3872 mStateLock.unlock();
3873 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003874 }
3875 write(fd, result.string(), result.size());
3876 return NO_ERROR;
3877}
3878
Dan Stozac7014012014-02-14 15:03:43 -08003879void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3880 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003881{
Robert Carr2047fae2016-11-28 14:09:09 -08003882 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003883 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003884 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003885}
3886
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003887void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003888 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003889{
3890 String8 name;
3891 if (index < args.size()) {
3892 name = String8(args[index]);
3893 index++;
3894 }
3895
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003896 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3897 getHwComposer().isConnected(displayId)) {
3898 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3899 const nsecs_t period = activeConfig->getVsyncPeriod();
3900 result.appendFormat("%" PRId64 "\n", period);
3901 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003902
3903 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003904 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003905 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003906 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003907 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003908 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003909 }
Robert Carr2047fae2016-11-28 14:09:09 -08003910 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003911 }
3912}
3913
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003914void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003915 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003916{
3917 String8 name;
3918 if (index < args.size()) {
3919 name = String8(args[index]);
3920 index++;
3921 }
3922
Robert Carr2047fae2016-11-28 14:09:09 -08003923 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003924 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003925 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003926 }
Robert Carr2047fae2016-11-28 14:09:09 -08003927 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003928
Svetoslavd85084b2014-03-20 10:28:31 -07003929 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003930}
3931
Jamie Gennis6547ff42013-07-16 20:12:42 -07003932// This should only be called from the main thread. Otherwise it would need
3933// the lock and should use mCurrentState rather than mDrawingState.
3934void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003935 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003936 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003937 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003938
3939 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3940}
3941
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003942void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003943{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003944 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003945
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003946 if (isLayerTripleBufferingDisabled())
3947 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003948
3949 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003950 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003951 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003952 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003953 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3954 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003955 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003956}
3957
Dan Stozab90cf072015-03-05 11:05:59 -08003958void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3959{
3960 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003961 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3962 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003963 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003964 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003965 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3966 b + 1, bucketTimeSec, percent);
3967 }
David Sodman4a36e932017-11-07 14:29:47 -08003968 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003969 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003970 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003971 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003972 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003973}
3974
Dan Stozae77c7662016-05-13 11:37:28 -07003975void SurfaceFlinger::recordBufferingStats(const char* layerName,
3976 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003977 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3978 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003979 for (const auto& segment : history) {
3980 if (!segment.usedThirdBuffer) {
3981 stats.twoBufferTime += segment.totalTime;
3982 }
3983 if (segment.occupancyAverage < 1.0f) {
3984 stats.doubleBufferedTime += segment.totalTime;
3985 } else if (segment.occupancyAverage < 2.0f) {
3986 stats.tripleBufferedTime += segment.totalTime;
3987 }
3988 ++stats.numSegments;
3989 stats.totalTime += segment.totalTime;
3990 }
3991}
3992
Brian Andersond6927fb2016-07-23 23:37:30 -07003993void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3994 result.appendFormat("Layer frame timestamps:\n");
3995
3996 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3997 const size_t count = currentLayers.size();
3998 for (size_t i=0 ; i<count ; i++) {
3999 currentLayers[i]->dumpFrameEvents(result);
4000 }
4001}
4002
Dan Stozae77c7662016-05-13 11:37:28 -07004003void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4004 result.append("Buffering stats:\n");
4005 result.append(" [Layer name] <Active time> <Two buffer> "
4006 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004007 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004008 typedef std::tuple<std::string, float, float, float> BufferTuple;
4009 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004010 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004011 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004012 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004013 if (stats.numSegments == 0) {
4014 continue;
4015 }
4016 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4017 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4018 stats.totalTime;
4019 float doubleBufferRatio = static_cast<float>(
4020 stats.doubleBufferedTime) / stats.totalTime;
4021 float tripleBufferRatio = static_cast<float>(
4022 stats.tripleBufferedTime) / stats.totalTime;
4023 sorted.insert({activeTime, {name, twoBufferRatio,
4024 doubleBufferRatio, tripleBufferRatio}});
4025 }
4026 for (const auto& sortedPair : sorted) {
4027 float activeTime = sortedPair.first;
4028 const BufferTuple& values = sortedPair.second;
4029 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4030 std::get<0>(values).c_str(), activeTime,
4031 std::get<1>(values), std::get<2>(values),
4032 std::get<3>(values));
4033 }
4034 result.append("\n");
4035}
4036
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004037void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004038 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004039 const int32_t displayId = display->getId();
4040 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4041 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004042 continue;
4043 }
4044
Dominik Laskowski7e045462018-05-30 13:02:02 -07004045 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004046 uint8_t port;
4047 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004048 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004049 result.append("no identification data\n");
4050 continue;
4051 }
4052
4053 if (!isEdid(data)) {
4054 result.append("unknown identification data: ");
4055 for (uint8_t byte : data) {
4056 result.appendFormat("%x ", byte);
4057 }
4058 result.append("\n");
4059 continue;
4060 }
4061
4062 const auto edid = parseEdid(data);
4063 if (!edid) {
4064 result.append("invalid EDID: ");
4065 for (uint8_t byte : data) {
4066 result.appendFormat("%x ", byte);
4067 }
4068 result.append("\n");
4069 continue;
4070 }
4071
4072 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4073 result.append(edid->displayName.data(), edid->displayName.length());
4074 result.append("\"\n");
4075 }
4076 result.append("\n");
4077}
4078
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004079void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4080 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004081 result.appendFormat("DisplayColorSetting: %s\n",
4082 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004083
4084 // TODO: print out if wide-color mode is active or not
4085
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004086 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004087 const int32_t displayId = display->getId();
4088 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004089 continue;
4090 }
4091
Dominik Laskowski7e045462018-05-30 13:02:02 -07004092 result.appendFormat("Display %d color modes:\n", displayId);
4093 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004094 for (auto&& mode : modes) {
4095 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4096 }
4097
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004098 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004099 result.appendFormat(" Current color mode: %s (%d)\n",
4100 decodeColorMode(currentMode).c_str(), currentMode);
4101 }
4102 result.append("\n");
4103}
4104
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004105LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004106 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004107 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4108 const State& state = useDrawing ? mDrawingState : mCurrentState;
4109 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004110 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004111 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004112 });
4113
4114 return layersProto;
4115}
4116
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004117LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004118 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004119
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004120 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004121 resolution->set_w(display.getWidth());
4122 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004123
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004124 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4125 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4126 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004127
Dominik Laskowski7e045462018-05-30 13:02:02 -07004128 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004129 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004130 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004131 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004132 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004133 }
4134 });
4135
4136 return layersProto;
4137}
4138
Mathias Agopian74d211a2013-04-22 16:55:35 +02004139void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4140 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004141{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004142 bool colorize = false;
4143 if (index < args.size()
4144 && (args[index] == String16("--color"))) {
4145 colorize = true;
4146 index++;
4147 }
4148
4149 Colorizer colorizer(colorize);
4150
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004151 // figure out if we're stuck somewhere
4152 const nsecs_t now = systemTime();
4153 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4154 const nsecs_t inTransaction(mDebugInTransaction);
4155 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4156 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4157
4158 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004159 * Dump library configuration.
4160 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004161
4162 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004163 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004164 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004165 appendSfConfigString(result);
4166 appendUiConfigString(result);
4167 appendGuiConfigString(result);
4168 result.append("\n");
4169
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004170 result.append("\nDisplay identification data:\n");
4171 dumpDisplayIdentificationData(result);
4172
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004173 result.append("\nWide-Color information:\n");
4174 dumpWideColorInfo(result);
4175
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004176 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004177 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004178 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004179 result.append(SyncFeatures::getInstance().toString());
4180 result.append("\n");
4181
Andy McFadden41d67d72014-04-25 16:58:34 -07004182 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004183 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004184 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004185
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004186 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4187 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004188 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4189 getHwComposer().isConnected(displayId)) {
4190 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004191 result.appendFormat("Display %d: "
4192 "app phase %" PRId64 " ns, "
4193 "sf phase %" PRId64 " ns, "
4194 "early app phase %" PRId64 " ns, "
4195 "early sf phase %" PRId64 " ns, "
4196 "early app gl phase %" PRId64 " ns, "
4197 "early sf gl phase %" PRId64 " ns, "
4198 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4199 displayId,
4200 vsyncPhaseOffsetNs,
4201 sfVsyncPhaseOffsetNs,
4202 appEarlyOffset,
4203 sfEarlyOffset,
4204 appEarlyGlOffset,
4205 sfEarlyOffset,
4206 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004207 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004208 result.append("\n");
4209
Dan Stozab90cf072015-03-05 11:05:59 -08004210 // Dump static screen stats
4211 result.append("\n");
4212 dumpStaticScreenStats(result);
4213 result.append("\n");
4214
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004215 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4216
Dan Stozae77c7662016-05-13 11:37:28 -07004217 dumpBufferingStats(result);
4218
Andy McFadden4803b742012-09-24 19:07:20 -07004219 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004220 * Dump the visible layer list
4221 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004222 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004223 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004224 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4225 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004226 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004227
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004228 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004229 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004230 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004231 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004232
4233 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004234 * Dump Display state
4235 */
4236
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004237 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004238 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004239 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004240 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004241 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004242 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004243 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004244
4245 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004246 * Dump SurfaceFlinger global state
4247 */
4248
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004249 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004250 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004251 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004252
Mathias Agopian888c8222012-08-04 21:10:38 -07004253 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004254 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004255
David Sodmanbc815282017-11-05 18:57:52 -08004256 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004257
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004258 if (display) {
4259 display->undefinedRegion.dump(result, "undefinedRegion");
4260 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4261 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004262 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004263 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4264 " last transaction time : %f us\n"
4265 " transaction-flags : %08x\n"
4266 " gpu_to_cpu_unsupported : %d\n",
4267 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4268 mTransactionFlags, !mGpuToCpuSupported);
4269
4270 if (display) {
4271 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4272 result.appendFormat(" refresh-rate : %f fps\n"
4273 " x-dpi : %f\n"
4274 " y-dpi : %f\n",
4275 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4276 activeConfig->getDpiY());
4277 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004278
Mathias Agopian74d211a2013-04-22 16:55:35 +02004279 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004280 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004281
Mathias Agopian74d211a2013-04-22 16:55:35 +02004282 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004283 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004284
4285 /*
4286 * VSYNC state
4287 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004288 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004289 result.append("\n");
4290
4291 /*
4292 * HWC layer minidump
4293 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004294 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004295 const int32_t displayId = display->getId();
4296 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004297 continue;
4298 }
4299
Dominik Laskowski7e045462018-05-30 13:02:02 -07004300 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004301 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004302 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004303 result.append("\n");
4304 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004305
4306 /*
4307 * Dump HWComposer state
4308 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004309 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004310 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004311 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004312 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004313 result.appendFormat(" h/w composer %s\n",
4314 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004315 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004316
4317 /*
4318 * Dump gralloc state
4319 */
4320 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4321 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004322
4323 /*
4324 * Dump VrFlinger state if in use.
4325 */
4326 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4327 result.append("VrFlinger state:\n");
4328 result.append(mVrFlinger->Dump().c_str());
4329 result.append("\n");
4330 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004331}
4332
Dominik Laskowski7e045462018-05-30 13:02:02 -07004333const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004334 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004335 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004336 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004337 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004338 }
4339 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004340
4341 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4342 static const Vector<sp<Layer>> empty;
4343 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004344}
4345
Keun young Park63f165f2012-08-31 10:53:36 -07004346bool SurfaceFlinger::startDdmConnection()
4347{
4348 void* libddmconnection_dso =
4349 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4350 if (!libddmconnection_dso) {
4351 return false;
4352 }
4353 void (*DdmConnection_start)(const char* name);
4354 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004355 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004356 if (!DdmConnection_start) {
4357 dlclose(libddmconnection_dso);
4358 return false;
4359 }
4360 (*DdmConnection_start)(getServiceName());
4361 return true;
4362}
4363
Chia-I Wu28f320b2018-05-03 11:02:56 -07004364void SurfaceFlinger::updateColorMatrixLocked() {
4365 mat4 colorMatrix;
4366 if (mGlobalSaturationFactor != 1.0f) {
4367 // Rec.709 luma coefficients
4368 float3 luminance{0.213f, 0.715f, 0.072f};
4369 luminance *= 1.0f - mGlobalSaturationFactor;
4370 mat4 saturationMatrix = mat4(
4371 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4372 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4373 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4374 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4375 );
4376 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4377 } else {
4378 colorMatrix = mClientColorMatrix * mDaltonizer();
4379 }
4380
4381 if (mCurrentState.colorMatrix != colorMatrix) {
4382 mCurrentState.colorMatrix = colorMatrix;
4383 mCurrentState.colorMatrixChanged = true;
4384 setTransactionFlags(eTransactionNeeded);
4385 }
4386}
4387
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004388status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004389 switch (code) {
4390 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004391 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004392 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004393 case CLEAR_ANIMATION_FRAME_STATS:
4394 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004395 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004396 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004397 case ENABLE_VSYNC_INJECTIONS:
4398 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004399 {
4400 // codes that require permission check
4401 IPCThreadState* ipc = IPCThreadState::self();
4402 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004403 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004404 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004405 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004406 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004407 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004408 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004409 break;
4410 }
Robert Carr1db73f62016-12-21 12:58:51 -08004411 /*
4412 * Calling setTransactionState is safe, because you need to have been
4413 * granted a reference to Client* and Handle* to do anything with it.
4414 *
4415 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4416 */
4417 case SET_TRANSACTION_STATE:
4418 case CREATE_SCOPED_CONNECTION:
4419 {
4420 return OK;
4421 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004422 case CAPTURE_SCREEN:
4423 {
4424 // codes that require permission check
4425 IPCThreadState* ipc = IPCThreadState::self();
4426 const int pid = ipc->getCallingPid();
4427 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004428 if ((uid != AID_GRAPHICS) &&
4429 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004430 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004431 return PERMISSION_DENIED;
4432 }
4433 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004434 }
chaviwa76b2712017-09-20 12:02:26 -07004435 case CAPTURE_LAYERS: {
4436 IPCThreadState* ipc = IPCThreadState::self();
4437 const int pid = ipc->getCallingPid();
4438 const int uid = ipc->getCallingUid();
4439 if ((uid != AID_GRAPHICS) &&
4440 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4441 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4442 return PERMISSION_DENIED;
4443 }
4444 break;
4445 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004446 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004447 return OK;
4448}
4449
4450status_t SurfaceFlinger::onTransact(
4451 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4452{
4453 status_t credentialCheck = CheckTransactCodeCredentials(code);
4454 if (credentialCheck != OK) {
4455 return credentialCheck;
4456 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004457
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004458 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4459 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004460 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004461 IPCThreadState* ipc = IPCThreadState::self();
4462 const int uid = ipc->getCallingUid();
4463 if (CC_UNLIKELY(uid != AID_SYSTEM
4464 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004465 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004466 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004467 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004468 return PERMISSION_DENIED;
4469 }
4470 int n;
4471 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004472 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004473 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004474 return NO_ERROR;
4475 case 1002: // SHOW_UPDATES
4476 n = data.readInt32();
4477 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004478 invalidateHwcGeometry();
4479 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004480 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004481 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004482 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004483 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004484 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004485 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004486 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004487 setTransactionFlags(
4488 eTransactionNeeded|
4489 eDisplayTransactionNeeded|
4490 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004491 return NO_ERROR;
4492 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004493 case 1006:{ // send empty update
4494 signalRefresh();
4495 return NO_ERROR;
4496 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004497 case 1008: // toggle use of hw composer
4498 n = data.readInt32();
4499 mDebugDisableHWC = n ? 1 : 0;
4500 invalidateHwcGeometry();
4501 repaintEverything();
4502 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004503 case 1009: // toggle use of transform hint
4504 n = data.readInt32();
4505 mDebugDisableTransformHint = n ? 1 : 0;
4506 invalidateHwcGeometry();
4507 repaintEverything();
4508 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004509 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004510 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004511 reply->writeInt32(0);
4512 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004513 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004514 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004515 return NO_ERROR;
4516 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004517 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004518 if (!display) {
4519 return NAME_NOT_FOUND;
4520 }
4521
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004522 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004523 return NO_ERROR;
4524 }
4525 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004526 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004527 // daltonize
4528 n = data.readInt32();
4529 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004530 case 1:
4531 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4532 break;
4533 case 2:
4534 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4535 break;
4536 case 3:
4537 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4538 break;
4539 default:
4540 mDaltonizer.setType(ColorBlindnessType::None);
4541 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004542 }
4543 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004544 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004545 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004546 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004547 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004548
4549 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004550 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004551 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004552 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004553 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004554 // apply a color matrix
4555 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004556 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004557 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004558 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004559 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004560 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004561 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004562 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004563 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004564 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004565 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004566
4567 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4568 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004569 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004570 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4571 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4572 }
4573
Chia-I Wu28f320b2018-05-03 11:02:56 -07004574 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004575 return NO_ERROR;
4576 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004577 // This is an experimental interface
4578 // Needs to be shifted to proper binder interface when we productize
4579 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004580 n = data.readInt32();
4581 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004582 return NO_ERROR;
4583 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004584 case 1017: {
4585 n = data.readInt32();
4586 mForceFullDamage = static_cast<bool>(n);
4587 return NO_ERROR;
4588 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004589 case 1018: { // Modify Choreographer's phase offset
4590 n = data.readInt32();
4591 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4592 return NO_ERROR;
4593 }
4594 case 1019: { // Modify SurfaceFlinger's phase offset
4595 n = data.readInt32();
4596 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4597 return NO_ERROR;
4598 }
Irvel468051e2016-06-13 16:44:44 -07004599 case 1020: { // Layer updates interceptor
4600 n = data.readInt32();
4601 if (n) {
4602 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004603 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004604 }
4605 else{
4606 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004607 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004608 }
4609 return NO_ERROR;
4610 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004611 case 1021: { // Disable HWC virtual displays
4612 n = data.readInt32();
4613 mUseHwcVirtualDisplays = !n;
4614 return NO_ERROR;
4615 }
Romain Guy0147a172017-06-01 13:53:56 -07004616 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004617 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004618 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004619
Chia-I Wu28f320b2018-05-03 11:02:56 -07004620 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004621 return NO_ERROR;
4622 }
Romain Guy54f154a2017-10-24 21:40:32 +01004623 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004624 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004625 invalidateHwcGeometry();
4626 repaintEverything();
4627 return NO_ERROR;
4628 }
4629 case 1024: { // Is wide color gamut rendering/color management supported?
4630 reply->writeBool(hasWideColorDisplay);
4631 return NO_ERROR;
4632 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004633 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004634 n = data.readInt32();
4635 if (n) {
4636 ALOGV("LayerTracing enabled");
4637 mTracing.enable();
4638 doTracing("tracing.enable");
4639 reply->writeInt32(NO_ERROR);
4640 } else {
4641 ALOGV("LayerTracing disabled");
4642 status_t err = mTracing.disable();
4643 reply->writeInt32(err);
4644 }
4645 return NO_ERROR;
4646 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004647 case 1026: { // Get layer tracing status
4648 reply->writeBool(mTracing.isEnabled());
4649 return NO_ERROR;
4650 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004651 // Is a DisplayColorSetting supported?
4652 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004653 const auto display = getDefaultDisplayDevice();
4654 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004655 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004656 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004657
4658 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4659 switch (setting) {
4660 case DisplayColorSetting::MANAGED:
4661 reply->writeBool(hasWideColorDisplay);
4662 break;
4663 case DisplayColorSetting::UNMANAGED:
4664 reply->writeBool(true);
4665 break;
4666 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004667 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004668 break;
4669 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004670 reply->writeBool(
4671 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004672 break;
4673 }
4674 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004675 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004676 // Is VrFlinger active?
4677 case 1028: {
4678 Mutex::Autolock _l(mStateLock);
4679 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4680 return NO_ERROR;
4681 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004682 }
4683 }
4684 return err;
4685}
4686
Steven Thomas6d8110b2017-08-31 18:24:21 -07004687void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004688 android_atomic_or(1, &mRepaintEverything);
4689 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004690}
4691
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004692// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4693class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004694public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004695 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4696 ~WindowDisconnector() {
4697 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004698 }
4699
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004700private:
4701 ANativeWindow* mWindow;
4702 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004703};
4704
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004705status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4706 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4707 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4708 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004709 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004710 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004711
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004712 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004713
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004714 const auto display = getDisplayDeviceLocked(displayToken);
4715 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004716
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004717 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004718
4719 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004720 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004721 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004722}
4723
4724status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004725 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004726 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004727 ATRACE_CALL();
4728
4729 class LayerRenderArea : public RenderArea {
4730 public:
Robert Carr578038f2018-03-09 12:25:24 -08004731 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4732 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004733 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004734 mLayer(layer),
4735 mCrop(crop),
4736 mFlinger(flinger),
4737 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004738 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004739 Rect getBounds() const override {
4740 const Layer::State& layerState(mLayer->getDrawingState());
4741 return Rect(layerState.active.w, layerState.active.h);
4742 }
4743 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4744 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4745 bool isSecure() const override { return false; }
4746 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004747 Rect getSourceCrop() const override {
4748 if (mCrop.isEmpty()) {
4749 return getBounds();
4750 } else {
4751 return mCrop;
4752 }
4753 }
Robert Carr578038f2018-03-09 12:25:24 -08004754 class ReparentForDrawing {
4755 public:
4756 const sp<Layer>& oldParent;
4757 const sp<Layer>& newParent;
4758
4759 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4760 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004761 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004762 }
Robert Carr15eae092018-03-23 13:43:53 -07004763 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004764 };
4765
4766 void render(std::function<void()> drawLayers) override {
4767 if (!mChildrenOnly) {
4768 mTransform = mLayer->getTransform().inverse();
4769 drawLayers();
4770 } else {
4771 Rect bounds = getBounds();
4772 screenshotParentLayer =
4773 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4774 bounds.getWidth(), bounds.getHeight(), 0);
4775
4776 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4777 drawLayers();
4778 }
4779 }
chaviwa76b2712017-09-20 12:02:26 -07004780
chaviwa76b2712017-09-20 12:02:26 -07004781 private:
chaviw7206d492017-11-10 16:16:12 -08004782 const sp<Layer> mLayer;
4783 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004784
4785 // In the "childrenOnly" case we reparent the children to a screenshot
4786 // layer which has no properties set and which does not draw.
4787 sp<ContainerLayer> screenshotParentLayer;
4788 Transform mTransform;
4789
4790 SurfaceFlinger* mFlinger;
4791 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004792 };
4793
4794 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4795 auto parent = layerHandle->owner.promote();
4796
chaviw7206d492017-11-10 16:16:12 -08004797 if (parent == nullptr || parent->isPendingRemoval()) {
4798 ALOGE("captureLayers called with a removed parent");
4799 return NAME_NOT_FOUND;
4800 }
4801
Robert Carr578038f2018-03-09 12:25:24 -08004802 const int uid = IPCThreadState::self()->getCallingUid();
4803 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4804 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4805 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4806 return PERMISSION_DENIED;
4807 }
4808
chaviw7206d492017-11-10 16:16:12 -08004809 Rect crop(sourceCrop);
4810 if (sourceCrop.width() <= 0) {
4811 crop.left = 0;
4812 crop.right = parent->getCurrentState().active.w;
4813 }
4814
4815 if (sourceCrop.height() <= 0) {
4816 crop.top = 0;
4817 crop.bottom = parent->getCurrentState().active.h;
4818 }
4819
4820 int32_t reqWidth = crop.width() * frameScale;
4821 int32_t reqHeight = crop.height() * frameScale;
4822
Robert Carr578038f2018-03-09 12:25:24 -08004823 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004824
Robert Carr578038f2018-03-09 12:25:24 -08004825 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004826 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4827 if (!layer->isVisible()) {
4828 return;
Robert Carr578038f2018-03-09 12:25:24 -08004829 } else if (childrenOnly && layer == parent.get()) {
4830 return;
chaviwa76b2712017-09-20 12:02:26 -07004831 }
4832 visitor(layer);
4833 });
4834 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004835 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004836}
4837
4838status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4839 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004840 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004841 bool useIdentityTransform) {
4842 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004843
Iris Chang7501ed62018-04-30 14:45:42 +08004844 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004845
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004846 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4847 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4848 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4849 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004850
4851 // This mutex protects syncFd and captureResult for communication of the return values from the
4852 // main thread back to this Binder thread
4853 std::mutex captureMutex;
4854 std::condition_variable captureCondition;
4855 std::unique_lock<std::mutex> captureLock(captureMutex);
4856 int syncFd = -1;
4857 std::optional<status_t> captureResult;
4858
Robert Carr03480e22018-01-04 16:02:06 -08004859 const int uid = IPCThreadState::self()->getCallingUid();
4860 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4861
Dominik Laskowski8c001672018-05-30 16:52:06 -07004862 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004863 // If there is a refresh pending, bug out early and tell the binder thread to try again
4864 // after the refresh.
4865 if (mRefreshPending) {
4866 ATRACE_NAME("Skipping screenshot for now");
4867 std::unique_lock<std::mutex> captureLock(captureMutex);
4868 captureResult = std::make_optional<status_t>(EAGAIN);
4869 captureCondition.notify_one();
4870 return;
4871 }
4872
4873 status_t result = NO_ERROR;
4874 int fd = -1;
4875 {
4876 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07004877 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08004878 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4879 useIdentityTransform, forSystem, &fd);
4880 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004881 }
4882
4883 {
4884 std::unique_lock<std::mutex> captureLock(captureMutex);
4885 syncFd = fd;
4886 captureResult = std::make_optional<status_t>(result);
4887 captureCondition.notify_one();
4888 }
4889 });
4890
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004891 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004892 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004893 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004894 while (*captureResult == EAGAIN) {
4895 captureResult.reset();
4896 result = postMessageAsync(message);
4897 if (result != NO_ERROR) {
4898 return result;
4899 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07004900 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004901 }
4902 result = *captureResult;
4903 }
4904
4905 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004906 sync_wait(syncFd, -1);
4907 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004908 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004909
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004910 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004911}
4912
chaviwa76b2712017-09-20 12:02:26 -07004913void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4914 TraverseLayersFunction traverseLayers, bool yswap,
4915 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004916 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004917
Lloyd Pique144e1162017-12-20 16:44:52 -08004918 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004919
4920 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004921 const auto raWidth = renderArea.getWidth();
4922 const auto raHeight = renderArea.getHeight();
4923
4924 const auto reqWidth = renderArea.getReqWidth();
4925 const auto reqHeight = renderArea.getReqHeight();
4926 Rect sourceCrop = renderArea.getSourceCrop();
4927
Iris Chang7501ed62018-04-30 14:45:42 +08004928 bool filtering = false;
4929 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4930 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
4931 static_cast<int32_t>(reqHeight) != raWidth;
4932 } else {
4933 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4934 static_cast<int32_t>(reqHeight) != raHeight;
4935 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004936
Dan Stozac1879002014-05-22 15:59:05 -07004937 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004938 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004939 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004940 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08004941 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4942 Transform tr;
4943 uint32_t flags = 0x00;
4944 switch (mPrimaryDisplayOrientation) {
4945 case DisplayState::eOrientation90:
4946 flags = Transform::ROT_90;
4947 break;
4948 case DisplayState::eOrientation180:
4949 flags = Transform::ROT_180;
4950 break;
4951 case DisplayState::eOrientation270:
4952 flags = Transform::ROT_270;
4953 break;
4954 }
4955 tr.set(flags, raWidth, raHeight);
4956 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07004957 }
4958
4959 // ensure that sourceCrop is inside screen
4960 if (sourceCrop.left < 0) {
4961 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4962 }
chaviwa76b2712017-09-20 12:02:26 -07004963 if (sourceCrop.right > raWidth) {
4964 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004965 }
4966 if (sourceCrop.top < 0) {
4967 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4968 }
chaviwa76b2712017-09-20 12:02:26 -07004969 if (sourceCrop.bottom > raHeight) {
4970 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004971 }
4972
Chia-I Wu36574d92018-05-16 10:54:36 -07004973 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
4974 engine.setOutputDataSpace(Dataspace::SRGB);
4975 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07004976
Mathias Agopian180f10d2013-04-10 22:55:41 -07004977 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004978 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004979
Iris Chang7501ed62018-04-30 14:45:42 +08004980 Transform::orientation_flags rotation = renderArea.getRotationFlags();
4981 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4982 // convert hw orientation into flag presentation
4983 // here inverse transform needed
4984 uint8_t hw_rot_90 = 0x00;
4985 uint8_t hw_flip_hv = 0x00;
4986 switch (mPrimaryDisplayOrientation) {
4987 case DisplayState::eOrientation90:
4988 hw_rot_90 = Transform::ROT_90;
4989 hw_flip_hv = Transform::ROT_180;
4990 break;
4991 case DisplayState::eOrientation180:
4992 hw_flip_hv = Transform::ROT_180;
4993 break;
4994 case DisplayState::eOrientation270:
4995 hw_rot_90 = Transform::ROT_90;
4996 break;
4997 }
4998
4999 // transform flags operation
5000 // 1) flip H V if both have ROT_90 flag
5001 // 2) XOR these flags
5002 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5003 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5004 if (rotation_rot_90 & hw_rot_90) {
5005 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5006 }
5007 rotation = static_cast<Transform::orientation_flags>
5008 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5009 }
5010
Mathias Agopian180f10d2013-04-10 22:55:41 -07005011 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005012 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005013 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005014 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005015
chaviw50da5042018-04-09 13:49:37 -07005016 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005017 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005018 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005019
chaviwa76b2712017-09-20 12:02:26 -07005020 traverseLayers([&](Layer* layer) {
5021 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07005022 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005023 if (filtering) layer->setFiltering(false);
5024 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005025}
5026
chaviwa76b2712017-09-20 12:02:26 -07005027status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5028 TraverseLayersFunction traverseLayers,
5029 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005030 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005031 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005032 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005033 ATRACE_CALL();
5034
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005035 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005036
5037 traverseLayers([&](Layer* layer) {
5038 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5039 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005040
Robert Carr03480e22018-01-04 16:02:06 -08005041 // We allow the system server to take screenshots of secure layers for
5042 // use in situations like the Screen-rotation animation and place
5043 // the impetus on WindowManager to not persist them.
5044 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005045 ALOGW("FB is protected: PERMISSION_DENIED");
5046 return PERMISSION_DENIED;
5047 }
5048
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005049 // this binds the given EGLImage as a framebuffer for the
5050 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005051 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005052 if (bufferBond.getStatus() != NO_ERROR) {
5053 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005054 return INVALID_OPERATION;
5055 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005056
Dan Stozaabcda352017-06-01 14:37:39 -07005057 // this will in fact render into our dequeued buffer
5058 // via an FBO, which means we didn't have to create
5059 // an EGLSurface and therefore we're not
5060 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005061 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005062
Dan Stozaabcda352017-06-01 14:37:39 -07005063 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005064 getRenderEngine().finish();
5065 *outSyncFd = -1;
5066
chaviwa76b2712017-09-20 12:02:26 -07005067 const auto reqWidth = renderArea.getReqWidth();
5068 const auto reqHeight = renderArea.getReqHeight();
5069
Dan Stozaabcda352017-06-01 14:37:39 -07005070 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5071 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005072 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005073 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005074 } else {
5075 base::unique_fd syncFd = getRenderEngine().flush();
5076 if (syncFd < 0) {
5077 getRenderEngine().finish();
5078 }
5079 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005080 }
5081
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005082 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005083}
5084
Mathias Agopiand5556842013-09-19 17:08:37 -07005085void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005086 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005087 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005088 for (size_t y = 0; y < h; y++) {
5089 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5090 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005091 if (p[x] != 0xFF000000) return;
5092 }
5093 }
chaviwa76b2712017-09-20 12:02:26 -07005094 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005095
Robert Carr2047fae2016-11-28 14:09:09 -08005096 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005097 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005098 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005099 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5100 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5101 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5102 static_cast<float>(state.color.a));
5103 i++;
5104 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005105 }
5106}
5107
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005108// ---------------------------------------------------------------------------
5109
Dan Stoza412903f2017-04-27 13:42:17 -07005110void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5111 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005112}
5113
Dan Stoza412903f2017-04-27 13:42:17 -07005114void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5115 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005116}
5117
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005118void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5119 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005120 const LayerVector::Visitor& visitor) {
5121 // We loop through the first level of layers without traversing,
5122 // as we need to interpret min/max layer Z in the top level Z space.
5123 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005124 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005125 continue;
5126 }
5127 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005128 // relative layers are traversed in Layer::traverseInZOrder
5129 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005130 continue;
5131 }
5132 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005133 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005134 return;
5135 }
chaviwa76b2712017-09-20 12:02:26 -07005136 if (!layer->isVisible()) {
5137 return;
5138 }
5139 visitor(layer);
5140 });
5141 }
5142}
5143
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005144}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005145
Chia-I Wu30505fb2018-03-26 16:20:31 -07005146
Mathias Agopian3f844832013-08-07 21:24:32 -07005147#if defined(__gl_h_)
5148#error "don't include gl/gl.h in this file"
5149#endif
5150
5151#if defined(__gl2_h_)
5152#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005153#endif