blob: 995a96e11a642e8fdc25a914213467978b3e15e2 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include "Effects/Daltonizer.h"
87
Mathias Agopian875d8e12013-06-07 15:35:48 -070088#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070089#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070090
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080092#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
93#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090094#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090095
chaviw1d044282017-09-27 12:19:28 -070096#include <layerproto/LayerProtoParser.h>
97
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080098#define DISPLAY_COUNT 1
99
Mathias Agopianfee2b462013-07-03 12:34:01 -0700100/*
101 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
102 * black pixels.
103 */
104#define DEBUG_SCREENSHOTS false
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107
Jaesoo Lee43518572017-01-23 19:03:16 +0900108using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700110using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700111using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700112using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700113using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
Steven Thomasb02664d2017-07-26 18:48:28 -0700115namespace {
116class ConditionalLock {
117public:
118 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
119 if (lock) {
120 mMutex.lock();
121 }
122 }
123 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
124private:
125 Mutex& mMutex;
126 bool mLocked;
127};
128} // namespace anonymous
129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130// ---------------------------------------------------------------------------
131
Mathias Agopian99b49842011-06-27 16:05:52 -0700132const String16 sHardwareTest("android.permission.HARDWARE_TEST");
133const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
134const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
135const String16 sDump("android.permission.DUMP");
136
137// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800138int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
139int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700140int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700141bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800142uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800143bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800144bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800145int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800146// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600147bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700148
Kalle Raitaa099a242017-01-11 11:17:29 -0800149
150std::string getHwcServiceName() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.hwc_service_name", value, "default");
153 ALOGI("Using HWComposer service: '%s'", value);
154 return std::string(value);
155}
156
157bool useTrebleTestingOverride() {
158 char value[PROPERTY_VALUE_MAX] = {};
159 property_get("debug.sf.treble_testing_override", value, "false");
160 ALOGI("Treble testing override: '%s'", value);
161 return std::string(value) == "true";
162}
163
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800164std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
165 switch(displayColorSetting) {
166 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700167 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800168 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700169 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800170 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700171 return std::string("Enhanced");
172 default:
173 return std::string("Unknown ") +
174 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800175 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800176}
177
Lloyd Pique99d3da52018-01-22 17:48:03 -0800178NativeWindowSurface::~NativeWindowSurface() = default;
179
180namespace impl {
181
182class NativeWindowSurface final : public android::NativeWindowSurface {
183public:
184 static std::unique_ptr<android::NativeWindowSurface> create(
185 const sp<IGraphicBufferProducer>& producer) {
186 return std::make_unique<NativeWindowSurface>(producer);
187 }
188
189 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
190 : surface(new Surface(producer, false)) {}
191
192 ~NativeWindowSurface() override = default;
193
194private:
195 sp<ANativeWindow> getNativeWindow() const override { return surface; }
196
197 void preallocateBuffers() override { surface->allocateBuffers(); }
198
199 sp<Surface> surface;
200};
201
202} // namespace impl
203
David Sodmanbc815282017-11-05 18:57:52 -0800204SurfaceFlingerBE::SurfaceFlingerBE()
205 : mHwcServiceName(getHwcServiceName()),
206 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800207 mFrameBuckets(),
208 mTotalTime(0),
209 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800210 mComposerSequenceId(0) {
211}
212
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800213SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800214 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800215 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700216 mTransactionPending(false),
217 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700218 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700219 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700220 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800221 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700222 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800224 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800225 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700227 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700228 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700229 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700230 mDebugInSwapBuffers(0),
231 mLastSwapBufferTime(0),
232 mDebugInTransaction(0),
233 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700234 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700235 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000236 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700237 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700238 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800239 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800240 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700241 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800242 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800243 mCreateBufferQueue(&BufferQueue::createBufferQueue),
244 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800245
246SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800247 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800248
249 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
250 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
251
252 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
253 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
254
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800255 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
256 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700258 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
259 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
260
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700261 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
262 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
263
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800264 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
265 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
266
Steven Thomas050b2c82017-03-06 11:45:16 -0800267 // Vr flinger is only enabled on Daydream ready devices.
268 useVrFlinger = getBool< ISurfaceFlingerConfigs,
269 &ISurfaceFlingerConfigs::useVrFlinger>(false);
270
Fabien Sanglard1971b632017-03-10 14:50:03 -0800271 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
272 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
273
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600274 hasWideColorDisplay =
275 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
276
Iris Chang7501ed62018-04-30 14:45:42 +0800277 V1_1::DisplayOrientation primaryDisplayOrientation =
278 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
279 V1_1::DisplayOrientation::ORIENTATION_0);
280
281 switch (primaryDisplayOrientation) {
282 case V1_1::DisplayOrientation::ORIENTATION_90:
283 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
284 break;
285 case V1_1::DisplayOrientation::ORIENTATION_180:
286 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
287 break;
288 case V1_1::DisplayOrientation::ORIENTATION_270:
289 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
290 break;
291 default:
292 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
293 break;
294 }
295 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
296
David Sodman99974d22017-11-28 12:04:33 -0800297 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700298
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299 // debugging stuff...
300 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700301
Mathias Agopianb4b17302013-03-20 18:36:41 -0700302 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700303 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700304
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 property_get("debug.sf.showupdates", value, "0");
306 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700307
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700308 property_get("debug.sf.ddms", value, "0");
309 mDebugDDMS = atoi(value);
310 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700311 if (!startDdmConnection()) {
312 // start failed, and DDMS debugging not enabled
313 mDebugDDMS = 0;
314 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700315 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700316 ALOGI_IF(mDebugRegion, "showupdates enabled");
317 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700318
319 property_get("debug.sf.disable_backpressure", value, "0");
320 mPropagateBackpressure = !atoi(value);
321 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700322
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800323 property_get("debug.sf.enable_hwc_vds", value, "0");
324 mUseHwcVirtualDisplays = atoi(value);
325 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800326
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800327 property_get("ro.sf.disable_triple_buffer", value, "1");
328 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800329 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700330
Yiwei Zhang243b3782018-05-15 17:40:04 -0700331 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700332 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
333 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
334
Dan Stoza84d619e2018-03-28 17:07:36 -0700335 property_get("debug.sf.early_phase_offset_ns", value, "0");
336 const int earlyWakeupOffsetOffsetNs = atoi(value);
337 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
338 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
339 sfVsyncPhaseOffsetNs);
340
Romain Guy11d63f42017-07-20 12:47:14 -0700341 // We should be reading 'persist.sys.sf.color_saturation' here
342 // but since /data may be encrypted, we need to wait until after vold
343 // comes online to attempt to read the property. The property is
344 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800345
346 if (useTrebleTestingOverride()) {
347 // Without the override SurfaceFlinger cannot connect to HIDL
348 // services that are not listed in the manifests. Considered
349 // deriving the setting from the set service name, but it
350 // would be brittle if the name that's not 'default' is used
351 // for production purposes later on.
352 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354}
355
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800356void SurfaceFlinger::onFirstRef()
357{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800358 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800359}
360
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800361SurfaceFlinger::~SurfaceFlinger()
362{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800363}
364
Dan Stozac7014012014-02-14 15:03:43 -0800365void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800366{
367 // the window manager died on us. prepare its eulogy.
368
Andy McFadden13a082e2012-08-24 10:16:42 -0700369 // restore initial conditions (default device unblank, etc)
370 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800371
372 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700373 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800374}
375
Robert Carr1db73f62016-12-21 12:58:51 -0800376static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700377 status_t err = client->initCheck();
378 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800379 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380 }
Robert Carr1db73f62016-12-21 12:58:51 -0800381 return nullptr;
382}
383
384sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
385 return initClient(new Client(this));
386}
387
388sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
389 const sp<IGraphicBufferProducer>& gbp) {
390 if (authenticateSurfaceTexture(gbp) == false) {
391 return nullptr;
392 }
393 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
394 if (layer == nullptr) {
395 return nullptr;
396 }
397
398 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800399}
400
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700401sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
402 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700403{
404 class DisplayToken : public BBinder {
405 sp<SurfaceFlinger> flinger;
406 virtual ~DisplayToken() {
407 // no more references, this display must be terminated
408 Mutex::Autolock _l(flinger->mStateLock);
409 flinger->mCurrentState.displays.removeItem(this);
410 flinger->setTransactionFlags(eDisplayTransactionNeeded);
411 }
412 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700413 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700414 : flinger(flinger) {
415 }
416 };
417
418 sp<BBinder> token = new DisplayToken(this);
419
420 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700421 DisplayDeviceState info;
422 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700423 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700424 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700425 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800426 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700427 return token;
428}
429
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700430void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700431 Mutex::Autolock _l(mStateLock);
432
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700433 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700434 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700435 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700436 return;
437 }
438
439 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700440 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700441 ALOGE("destroyDisplay called for non-virtual display");
442 return;
443 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700444 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700445 mCurrentState.displays.removeItemsAt(idx);
446 setTransactionFlags(eDisplayTransactionNeeded);
447}
448
Mathias Agopiane57f2922012-08-09 16:29:12 -0700449sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700450 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700451 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800452 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700453 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700454 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700455}
456
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800457void SurfaceFlinger::bootFinished()
458{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700459 if (mStartPropertySetThread->join() != NO_ERROR) {
460 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800461 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800462 const nsecs_t now = systemTime();
463 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000464 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700465
466 // wait patiently for the window manager death
467 const String16 name("window");
468 sp<IBinder> window(defaultServiceManager()->getService(name));
469 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700470 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700471 }
472
Steven Thomas050b2c82017-03-06 11:45:16 -0800473 if (mVrFlinger) {
474 mVrFlinger->OnBootFinished();
475 }
476
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700477 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700478 // formerly we would just kill the process, but we now ask it to exit so it
479 // can choose where to stop the animation.
480 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700481
482 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
483 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
484 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700485
Thierry Strudel2924d012017-08-14 15:19:37 -0700486 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700487 readPersistentProperties();
488 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700489 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800490}
491
Mathias Agopian3f844832013-08-07 21:24:32 -0700492void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700493 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800494 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700495 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700496 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800497 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
498 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700499 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700500 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700501 return true;
502 }
503 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700504 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700505}
506
Lloyd Piquee83f9312018-02-01 12:53:17 -0800507class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700508public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700509 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000510 const char* name) :
511 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700512 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700513 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000514 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
515 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700516 mDispSync(dispSync),
517 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700518 mVsyncMutex(),
519 mPhaseOffset(phaseOffset),
520 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700521
Lloyd Piquee83f9312018-02-01 12:53:17 -0800522 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700523
Lloyd Piquee83f9312018-02-01 12:53:17 -0800524 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700525 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700526 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000527 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700528 static_cast<DispSync::Callback*>(this));
529 if (err != NO_ERROR) {
530 ALOGE("error registering vsync callback: %s (%d)",
531 strerror(-err), err);
532 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700533 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534 } else {
535 status_t err = mDispSync->removeEventListener(
536 static_cast<DispSync::Callback*>(this));
537 if (err != NO_ERROR) {
538 ALOGE("error unregistering vsync callback: %s (%d)",
539 strerror(-err), err);
540 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700541 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700543 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700544 }
545
Lloyd Piquee83f9312018-02-01 12:53:17 -0800546 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700547 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700548 mCallback = callback;
549 }
550
Lloyd Piquee83f9312018-02-01 12:53:17 -0800551 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700552 Mutex::Autolock lock(mVsyncMutex);
553
554 // Normalize phaseOffset to [0, period)
555 auto period = mDispSync->getPeriod();
556 phaseOffset %= period;
557 if (phaseOffset < 0) {
558 // If we're here, then phaseOffset is in (-period, 0). After this
559 // operation, it will be in (0, period)
560 phaseOffset += period;
561 }
562 mPhaseOffset = phaseOffset;
563
564 // If we're not enabled, we don't need to mess with the listeners
565 if (!mEnabled) {
566 return;
567 }
568
Dan Stoza84d619e2018-03-28 17:07:36 -0700569 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
570 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700571 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700572 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700573 strerror(-err), err);
574 }
575 }
576
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577private:
578 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800579 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700580 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700581 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700582 callback = mCallback;
583
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700584 if (mTraceVsync) {
585 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700586 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700587 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588 }
589
Peiyong Lin566a3b42018-01-09 18:22:43 -0800590 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700591 callback->onVSyncEvent(when);
592 }
593 }
594
Tim Murray4a4e4a22016-04-19 16:29:23 +0000595 const char* const mName;
596
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700597 int mValue;
598
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700599 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700600 const String8 mVsyncOnLabel;
601 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700602
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700603 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700604
605 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800606 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700607
608 Mutex mVsyncMutex; // Protects the following
609 nsecs_t mPhaseOffset;
610 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700611};
612
Lloyd Piquee83f9312018-02-01 12:53:17 -0800613class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700614public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800615 InjectVSyncSource() = default;
616 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700617
Lloyd Piquee83f9312018-02-01 12:53:17 -0800618 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700619 std::lock_guard<std::mutex> lock(mCallbackMutex);
620 mCallback = callback;
621 }
622
Lloyd Piquee83f9312018-02-01 12:53:17 -0800623 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700624 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700625 if (mCallback) {
626 mCallback->onVSyncEvent(when);
627 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700628 }
629
Lloyd Piquee83f9312018-02-01 12:53:17 -0800630 void setVSyncEnabled(bool) override {}
631 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700632
633private:
634 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800635 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700636};
637
Wei Wangf9b05ee2017-07-19 20:59:39 -0700638// Do not call property_set on main thread which will be blocked by init
639// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700640void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700641 ALOGI( "SurfaceFlinger's main thread ready to run. "
642 "Initializing graphics H/W...");
643
Thierry Strudel2924d012017-08-14 15:19:37 -0700644 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900645
Steven Thomasb02664d2017-07-26 18:48:28 -0700646 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800647
Steven Thomasb02664d2017-07-26 18:48:28 -0700648 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800649 mEventThreadSource =
650 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
651 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800652 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
653 [this]() { resyncWithRateLimit(); },
654 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800655 "appEventThread");
656 mSfEventThreadSource =
657 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
658 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800659
Lloyd Pique24b0a482018-03-09 18:52:26 -0800660 mSFEventThread =
661 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
662 [this]() { resyncWithRateLimit(); },
663 [this](nsecs_t timestamp) {
664 mInterceptor->saveVSyncEvent(timestamp);
665 },
666 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800667 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza84d619e2018-03-28 17:07:36 -0700668 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800669
Steven Thomasb02664d2017-07-26 18:48:28 -0700670 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800671 getBE().mRenderEngine =
672 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
673 hasWideColorDisplay
674 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
675 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800676 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700677
678 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
679 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800680 getBE().mHwc.reset(
681 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700682 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800683 // Process any initial hotplug and resulting display changes.
684 processDisplayHotplugEventsLocked();
685 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
686 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800687
Lloyd Piquefcd86612017-12-14 17:15:36 -0800688 // make the default display GLContext current so that we can create textures
689 // when creating Layers (which may happens before we render something)
690 getDefaultDisplayDeviceLocked()->makeCurrent();
691
Steven Thomas050b2c82017-03-06 11:45:16 -0800692 if (useVrFlinger) {
693 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700694 // This callback is called from the vr flinger dispatch thread. We
695 // need to call signalTransaction(), which requires holding
696 // mStateLock when we're not on the main thread. Acquiring
697 // mStateLock from the vr flinger dispatch thread might trigger a
698 // deadlock in surface flinger (see b/66916578), so post a message
699 // to be handled on the main thread instead.
700 sp<LambdaMessage> message = new LambdaMessage([=]() {
701 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
702 mVrFlingerRequestsDisplay = requestDisplay;
703 signalTransaction();
704 });
705 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800706 };
David Sodman105b7dc2017-11-04 20:28:14 -0700707 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
708 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800709 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800710 if (!mVrFlinger) {
711 ALOGE("Failed to start vrflinger");
712 }
713 }
714
Lloyd Pique379adc12018-01-22 17:31:47 -0800715 mEventControlThread = std::make_unique<impl::EventControlThread>(
716 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700717
Mathias Agopian92a979a2012-08-02 18:32:23 -0700718 // initialize our drawing state
719 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700720
Andy McFadden13a082e2012-08-24 10:16:42 -0700721 // set initial conditions (e.g. unblank default device)
722 initializeDisplays();
723
David Sodmanbc815282017-11-05 18:57:52 -0800724 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700725
Wei Wangf9b05ee2017-07-19 20:59:39 -0700726 // Inform native graphics APIs whether the present timestamp is supported:
727 if (getHwComposer().hasCapability(
728 HWC2::Capability::PresentFenceIsNotReliable)) {
729 mStartPropertySetThread = new StartPropertySetThread(false);
730 } else {
731 mStartPropertySetThread = new StartPropertySetThread(true);
732 }
733
734 if (mStartPropertySetThread->Start() != NO_ERROR) {
735 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800736 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800737
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800738 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
739 Dataspace::SRGB_LINEAR);
740
Dan Stoza9e56aa02015-11-02 13:00:03 -0800741 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700742}
743
Romain Guy11d63f42017-07-20 12:47:14 -0700744void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700745 Mutex::Autolock _l(mStateLock);
746
Romain Guy11d63f42017-07-20 12:47:14 -0700747 char value[PROPERTY_VALUE_MAX];
748
749 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800750 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700751 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800752 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100753
754 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700755 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700756}
757
Mathias Agopiana67e4182012-06-19 17:26:12 -0700758void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800759 // Start boot animation service by setting a property mailbox
760 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700761 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800762 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700763 if (mStartPropertySetThread->join() != NO_ERROR) {
764 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800765 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700766}
767
Mathias Agopian875d8e12013-06-07 15:35:48 -0700768size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800769 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700770}
771
Mathias Agopian875d8e12013-06-07 15:35:48 -0700772size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800773 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700774}
775
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800776// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800777
Jamie Gennis582270d2011-08-17 18:19:00 -0700778bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800779 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800780 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800781 return authenticateSurfaceTextureLocked(bufferProducer);
782}
783
784bool SurfaceFlinger::authenticateSurfaceTextureLocked(
785 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800786 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800787 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800788}
789
Brian Anderson6b376712017-04-04 10:51:39 -0700790status_t SurfaceFlinger::getSupportedFrameTimestamps(
791 std::vector<FrameEvent>* outSupported) const {
792 *outSupported = {
793 FrameEvent::REQUESTED_PRESENT,
794 FrameEvent::ACQUIRE,
795 FrameEvent::LATCH,
796 FrameEvent::FIRST_REFRESH_START,
797 FrameEvent::LAST_REFRESH_START,
798 FrameEvent::GPU_COMPOSITION_DONE,
799 FrameEvent::DEQUEUE_READY,
800 FrameEvent::RELEASE,
801 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700802 ConditionalLock _l(mStateLock,
803 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700804 if (!getHwComposer().hasCapability(
805 HWC2::Capability::PresentFenceIsNotReliable)) {
806 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
807 }
808 return NO_ERROR;
809}
810
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700811status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
812 Vector<DisplayInfo>* configs) {
813 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700814 return BAD_VALUE;
815 }
816
Jesse Hall692c7232012-11-08 15:41:56 -0800817 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700818 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
819 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700820 type = i;
821 break;
822 }
823 }
824
825 if (type < 0) {
826 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700827 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 // TODO: Not sure if display density should handled by SF any longer
830 class Density {
831 static int getDensityFromProperty(char const* propName) {
832 char property[PROPERTY_VALUE_MAX];
833 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800834 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 density = atoi(property);
836 }
837 return density;
838 }
839 public:
840 static int getEmuDensity() {
841 return getDensityFromProperty("qemu.sf.lcd_density"); }
842 static int getBuildDensity() {
843 return getDensityFromProperty("ro.sf.lcd_density"); }
844 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700845
Dan Stoza7f7da322014-05-02 15:26:25 -0700846 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700847
Steven Thomas6d8110b2017-08-31 18:24:21 -0700848 ConditionalLock _l(mStateLock,
849 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700851 DisplayInfo info = DisplayInfo();
852
Dan Stoza9e56aa02015-11-02 13:00:03 -0800853 float xdpi = hwConfig->getDpiX();
854 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700855
856 if (type == DisplayDevice::DISPLAY_PRIMARY) {
857 // The density of the device is provided by a build property
858 float density = Density::getBuildDensity() / 160.0f;
859 if (density == 0) {
860 // the build doesn't provide a density -- this is wrong!
861 // use xdpi instead
862 ALOGE("ro.sf.lcd_density must be defined as a build property");
863 density = xdpi / 160.0f;
864 }
865 if (Density::getEmuDensity()) {
866 // if "qemu.sf.lcd_density" is specified, it overrides everything
867 xdpi = ydpi = density = Density::getEmuDensity();
868 density /= 160.0f;
869 }
870 info.density = density;
871
872 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700873 const auto display = getDefaultDisplayDeviceLocked();
874 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 } else {
876 // TODO: where should this value come from?
877 static const int TV_DENSITY = 213;
878 info.density = TV_DENSITY / 160.0f;
879 info.orientation = 0;
880 }
881
Dan Stoza9e56aa02015-11-02 13:00:03 -0800882 info.w = hwConfig->getWidth();
883 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700884 info.xdpi = xdpi;
885 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900887 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888
Andy McFadden91b2ca82014-06-13 14:04:23 -0700889 // This is how far in advance a buffer must be queued for
890 // presentation at a given time. If you want a buffer to appear
891 // on the screen at time N, you must submit the buffer before
892 // (N - presentationDeadline).
893 //
894 // Normally it's one full refresh period (to give SF a chance to
895 // latch the buffer), but this can be reduced by configuring a
896 // DispSync offset. Any additional delays introduced by the hardware
897 // composer or panel must be accounted for here.
898 //
899 // We add an additional 1ms to allow for processing time and
900 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800901 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800902 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700903
904 // All non-virtual displays are currently considered secure.
905 info.secure = true;
906
Iris Chang7501ed62018-04-30 14:45:42 +0800907 if (type == DisplayDevice::DISPLAY_PRIMARY &&
908 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
909 std::swap(info.w, info.h);
910 }
911
Michael Wright28f24d02016-07-12 13:30:53 -0700912 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700913 }
914
Dan Stoza7f7da322014-05-02 15:26:25 -0700915 return NO_ERROR;
916}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
919 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700920 return BAD_VALUE;
921 }
922
923 // FIXME for now we always return stats for the primary display
924 memset(stats, 0, sizeof(*stats));
925 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
926 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
927 return NO_ERROR;
928}
929
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700930int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
931 const auto display = getDisplayDevice(displayToken);
932 if (!display) {
933 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800934 return BAD_VALUE;
935 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700936
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700937 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700938}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
941 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700942 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700943 return;
944 }
945
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700946 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700947 ALOGW("Trying to set config for virtual display");
948 return;
949 }
950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951 display->setActiveConfig(mode);
952 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700953}
954
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700955status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
956 postMessageSync(new LambdaMessage([&]() {
957 Vector<DisplayInfo> configs;
958 getDisplayConfigs(displayToken, &configs);
959 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
960 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
961 configs.size());
962 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700963 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700964 const auto display = getDisplayDevice(displayToken);
965 if (!display) {
966 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
967 displayToken.get());
968 } else if (display->isVirtual()) {
969 ALOGW("Attempt to set active config %d for virtual display", mode);
970 } else {
971 setActiveConfigInternal(display, mode);
972 }
973 }));
974
Mathias Agopian888c8222012-08-04 21:10:38 -0700975 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700976}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700977status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
978 Vector<ColorMode>* outColorModes) {
979 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700980 return BAD_VALUE;
981 }
982
Michael Wright28f24d02016-07-12 13:30:53 -0700983 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700984 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
985 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700986 type = i;
987 break;
988 }
989 }
990
991 if (type < 0) {
992 return type;
993 }
994
Peiyong Lina52f0292018-03-14 17:26:31 -0700995 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700996 {
997 ConditionalLock _l(mStateLock,
998 std::this_thread::get_id() != mMainThreadId);
999 modes = getHwComposer().getColorModes(type);
1000 }
Michael Wright28f24d02016-07-12 13:30:53 -07001001 outColorModes->clear();
1002 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1003
1004 return NO_ERROR;
1005}
1006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001007ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1008 if (const auto display = getDisplayDevice(displayToken)) {
1009 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001010 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001011 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001012}
1013
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001014void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1015 Dataspace dataSpace, RenderIntent renderIntent) {
1016 ColorMode currentMode = display->getActiveColorMode();
1017 Dataspace currentDataSpace = display->getCompositionDataSpace();
1018 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001019
Peiyong Lin38e9a562018-04-10 16:24:20 -07001020 if (mode == currentMode && dataSpace == currentDataSpace &&
1021 renderIntent == currentRenderIntent) {
1022 return;
1023 }
1024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001026 ALOGW("Trying to set config for virtual display");
1027 return;
1028 }
1029
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001030 display->setActiveColorMode(mode);
1031 display->setCompositionDataSpace(dataSpace);
1032 display->setActiveRenderIntent(renderIntent);
1033 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001034
1035 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001036 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1037 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001038}
1039
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001040status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
1041 postMessageSync(new LambdaMessage([&]() {
1042 Vector<ColorMode> modes;
1043 getDisplayColorModes(displayToken, &modes);
1044 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1045 if (mode < ColorMode::NATIVE || !exists) {
1046 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1047 decodeColorMode(mode).c_str(), mode, displayToken.get());
1048 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001049 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050 const auto display = getDisplayDevice(displayToken);
1051 if (!display) {
1052 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1053 decodeColorMode(mode).c_str(), mode, displayToken.get());
1054 } else if (display->isVirtual()) {
1055 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1056 decodeColorMode(mode).c_str(), mode);
1057 } else {
1058 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1059 RenderIntent::COLORIMETRIC);
1060 }
1061 }));
1062
Michael Wright28f24d02016-07-12 13:30:53 -07001063 return NO_ERROR;
1064}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001065
Svetoslavd85084b2014-03-20 10:28:31 -07001066status_t SurfaceFlinger::clearAnimationFrameStats() {
1067 Mutex::Autolock _l(mStateLock);
1068 mAnimFrameTracker.clearStats();
1069 return NO_ERROR;
1070}
1071
1072status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1073 Mutex::Autolock _l(mStateLock);
1074 mAnimFrameTracker.getStats(outStats);
1075 return NO_ERROR;
1076}
1077
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001078status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1079 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001080 Mutex::Autolock _l(mStateLock);
1081
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001082 const auto display = getDisplayDeviceLocked(displayToken);
1083 if (!display) {
1084 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001085 return BAD_VALUE;
1086 }
1087
Peiyong Linfb069302018-04-25 14:34:31 -07001088 // At this point the DisplayDeivce should already be set up,
1089 // meaning the luminance information is already queried from
1090 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001091 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001092 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1093 capabilities.getDesiredMaxLuminance(),
1094 capabilities.getDesiredMaxAverageLuminance(),
1095 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001096
1097 return NO_ERROR;
1098}
1099
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001100status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001101 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1102 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001103
Chia-I Wu90f669f2017-10-05 14:24:41 -07001104 if (mInjectVSyncs == enable) {
1105 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001106 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001107
1108 if (enable) {
1109 ALOGV("VSync Injections enabled");
1110 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001111 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001112 mInjectorEventThread = std::make_unique<
1113 impl::EventThread>(mVSyncInjector.get(),
1114 [this]() { resyncWithRateLimit(); },
1115 impl::EventThread::InterceptVSyncsCallback(),
1116 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001117 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001118 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001119 } else {
1120 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001121 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001122 }
1123
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001124 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001125 });
1126 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001127 return NO_ERROR;
1128}
1129
1130status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001131 Mutex::Autolock _l(mStateLock);
1132
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001133 if (!mInjectVSyncs) {
1134 ALOGE("VSync Injections not enabled");
1135 return BAD_VALUE;
1136 }
1137 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1138 ALOGV("Injecting VSync inside SurfaceFlinger");
1139 mVSyncInjector->onInjectSyncEvent(when);
1140 }
1141 return NO_ERROR;
1142}
1143
Lloyd Pique755e3192018-01-31 16:46:15 -08001144status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1145 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001146 IPCThreadState* ipc = IPCThreadState::self();
1147 const int pid = ipc->getCallingPid();
1148 const int uid = ipc->getCallingUid();
1149 if ((uid != AID_SHELL) &&
1150 !PermissionCache::checkPermission(sDump, pid, uid)) {
1151 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1152 return PERMISSION_DENIED;
1153 }
1154
1155 // Try to acquire a lock for 1s, fail gracefully
1156 const status_t err = mStateLock.timedLock(s2ns(1));
1157 const bool locked = (err == NO_ERROR);
1158 if (!locked) {
1159 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1160 return TIMED_OUT;
1161 }
1162
1163 outLayers->clear();
1164 mCurrentState.traverseInZOrder([&](Layer* layer) {
1165 outLayers->push_back(layer->getLayerDebugInfo());
1166 });
1167
1168 mStateLock.unlock();
1169 return NO_ERROR;
1170}
1171
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001172// ----------------------------------------------------------------------------
1173
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001174sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1175 ISurfaceComposer::VsyncSource vsyncSource) {
1176 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1177 return mSFEventThread->createEventConnection();
1178 } else {
1179 return mEventThread->createEventConnection();
1180 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001181}
1182
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001183// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001184
1185void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001186 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001187}
1188
1189void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001190 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001191}
1192
1193void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001194 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001195}
1196
1197void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001198 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001199 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001200}
1201
1202status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001203 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001204 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001205}
1206
1207status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001208 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001209 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001210 if (res == NO_ERROR) {
1211 msg->wait();
1212 }
1213 return res;
1214}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001215
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001216void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001217 do {
1218 waitForEvent();
1219 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001220}
1221
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001222void SurfaceFlinger::enableHardwareVsync() {
1223 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001224 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001226 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1227 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001229 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001230}
1231
Jesse Hall948fe0c2013-10-14 12:56:09 -07001232void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233 Mutex::Autolock _l(mHWVsyncLock);
1234
Jesse Hall948fe0c2013-10-14 12:56:09 -07001235 if (makeAvailable) {
1236 mHWVsyncAvailable = true;
1237 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001238 // Hardware vsync is not currently available, so abort the resync
1239 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001240 return;
1241 }
1242
David Sodman105b7dc2017-11-04 20:28:14 -07001243 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001244 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001245
1246 mPrimaryDispSync.reset();
1247 mPrimaryDispSync.setPeriod(period);
1248
1249 if (!mPrimaryHWVsyncEnabled) {
1250 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001251 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1252 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001253 mPrimaryHWVsyncEnabled = true;
1254 }
1255}
1256
Jesse Hall948fe0c2013-10-14 12:56:09 -07001257void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001258 Mutex::Autolock _l(mHWVsyncLock);
1259 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001260 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1261 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262 mPrimaryDispSync.endResync();
1263 mPrimaryHWVsyncEnabled = false;
1264 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001265 if (makeUnavailable) {
1266 mHWVsyncAvailable = false;
1267 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001268}
1269
Tim Murray4a4e4a22016-04-19 16:29:23 +00001270void SurfaceFlinger::resyncWithRateLimit() {
1271 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001272
1273 // No explicit locking is needed here since EventThread holds a lock while calling this method
1274 static nsecs_t sLastResyncAttempted = 0;
1275 const nsecs_t now = systemTime();
1276 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001277 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001278 }
Dan Stoza57164302017-05-08 14:03:54 -07001279 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001280}
1281
Steven Thomasb02664d2017-07-26 18:48:28 -07001282void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1283 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001284 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001285 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001286 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001287 return;
1288 }
1289
1290 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001291 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001292 return;
1293 }
1294
Jamie Gennisd1700752013-10-14 12:22:52 -07001295 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296
Jamie Gennisd1700752013-10-14 12:22:52 -07001297 { // Scope for the lock
1298 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001299 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001300 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001301 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001302 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001303
1304 if (needsHwVsync) {
1305 enableHardwareVsync();
1306 } else {
1307 disableHardwareVsync(false);
1308 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001309}
1310
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001311void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001312 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1313 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001314}
1315
Lloyd Pique715a2c12017-12-14 17:18:08 -08001316void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1317 HWC2::Connection connection) {
1318 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1319 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001320
Lloyd Piqueba04e622017-12-14 17:11:26 -08001321 // Ignore events that do not have the right sequenceId.
1322 if (sequenceId != getBE().mComposerSequenceId) {
1323 return;
1324 }
1325
Steven Thomasb02664d2017-07-26 18:48:28 -07001326 // Only lock if we're not on the main thread. This function is normally
1327 // called on a hwbinder thread, but for the primary display it's called on
1328 // the main thread with the state lock already held, so don't attempt to
1329 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001330 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001331
Lloyd Pique715a2c12017-12-14 17:18:08 -08001332 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001333
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001334 if (std::this_thread::get_id() == mMainThreadId) {
1335 // Process all pending hot plug events immediately if we are on the main thread.
1336 processDisplayHotplugEventsLocked();
1337 }
1338
Lloyd Piqueba04e622017-12-14 17:11:26 -08001339 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001340}
1341
Steven Thomasb02664d2017-07-26 18:48:28 -07001342void SurfaceFlinger::onRefreshReceived(int sequenceId,
1343 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001344 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001345 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001347 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001348 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001349}
1350
Dan Stoza9e56aa02015-11-02 13:00:03 -08001351void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001352 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001353 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001354 getHwComposer().setVsyncEnabled(disp,
1355 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001356}
1357
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001358// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001359void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001360 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001361 // Clear the drawing state so that the logic inside of
1362 // handleTransactionLocked will fire. It will determine the delta between
1363 // mCurrentState and mDrawingState and re-apply all changes when we make the
1364 // transition.
1365 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001366 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001367 mDisplays.clear();
1368}
1369
Steven Thomas050b2c82017-03-06 11:45:16 -08001370void SurfaceFlinger::updateVrFlinger() {
1371 if (!mVrFlinger)
1372 return;
1373 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001374 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001375 return;
1376 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001377
David Sodman105b7dc2017-11-04 20:28:14 -07001378 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 ALOGE("Vr flinger is only supported for remote hardware composer"
1380 " service connections. Ignoring request to transition to vr"
1381 " flinger.");
1382 mVrFlingerRequestsDisplay = false;
1383 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001384 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001385
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001386 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001388 int currentDisplayPowerMode = getDefaultDisplayDeviceLocked()->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001389
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001391 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001392 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001393
Steven Thomasb02664d2017-07-26 18:48:28 -07001394 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001395 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001396 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1397 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001398 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001399
David Sodman105b7dc2017-11-04 20:28:14 -07001400 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1401 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001402
1403 if (vrFlingerRequestsDisplay) {
1404 mVrFlinger->GrantDisplayOwnership();
1405 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001406 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001408
1409 mVisibleRegionsDirty = true;
1410 invalidateHwcGeometry();
1411
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001412 // Re-enable default display.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001413 setPowerModeInternal(getDefaultDisplayDeviceLocked(), currentDisplayPowerMode,
1414 /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001415
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001417 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 const nsecs_t period = activeConfig->getVsyncPeriod();
1419 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001420
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 // Use phase of 0 since phase is not known.
1422 // Use latency of 0, which will snap to the ideal latency.
1423 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001424
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001425 android_atomic_or(1, &mRepaintEverything);
1426 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001427}
1428
Mathias Agopian4fec8732012-06-29 14:12:52 -07001429void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001430 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001431 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001432 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001433 bool frameMissed = !mHadClientComposition &&
1434 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001435 (mPreviousPresentFence->getSignalTime() ==
1436 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001437 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001438 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001439 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001440 mTimeStats.incrementMissedFrames();
1441 if (mPropagateBackpressure) {
1442 signalLayerUpdate();
1443 break;
1444 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001445 }
Dan Stoza50182882016-07-08 12:02:20 -07001446
Steven Thomas050b2c82017-03-06 11:45:16 -08001447 // Now that we're going to make it to the handleMessageTransaction()
1448 // call below it's safe to call updateVrFlinger(), which will
1449 // potentially trigger a display handoff.
1450 updateVrFlinger();
1451
Dan Stoza6b9454d2014-11-07 16:00:59 -08001452 bool refreshNeeded = handleMessageTransaction();
1453 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001454 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001455 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001456 // Signal a refresh if a transaction modified the window state,
1457 // a new buffer was latched, or if HWC has requested a full
1458 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001459 signalRefresh();
1460 }
1461 break;
1462 }
1463 case MessageQueue::REFRESH: {
1464 handleMessageRefresh();
1465 break;
1466 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001467 }
1468}
1469
Dan Stoza6b9454d2014-11-07 16:00:59 -08001470bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001471 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001472 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001473 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001474 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001475 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001476 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001477}
1478
Dan Stoza6b9454d2014-11-07 16:00:59 -08001479bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001480 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001481 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001482}
1483
1484void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001485 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001486
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001487 mRefreshPending = false;
1488
Chia-I Wu30505fb2018-03-26 16:20:31 -07001489 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001490
Chia-I Wu30505fb2018-03-26 16:20:31 -07001491 preComposition(refreshStartTime);
1492 rebuildLayerStacks();
1493 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001494 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001495 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001496 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001497 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001498 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001499
David Sodman105b7dc2017-11-04 20:28:14 -07001500 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001501
1502 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001503 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001504 mHadClientComposition = mHadClientComposition ||
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001505 getBE().mHwc->hasClientComposition(display->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001506 }
Dan Stoza84d619e2018-03-28 17:07:36 -07001507 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001508
Dan Stoza9e56aa02015-11-02 13:00:03 -08001509 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001510}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001511
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512void SurfaceFlinger::doDebugFlashRegions()
1513{
1514 // is debugging enabled
1515 if (CC_LIKELY(!mDebugRegion))
1516 return;
1517
1518 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001519 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001520 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001521 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001522 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001523 if (!dirtyRegion.isEmpty()) {
1524 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001525 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001526
1527 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001528 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001529 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001530 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1531
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001532 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001533 }
1534 }
1535 }
1536
1537 postFramebuffer();
1538
1539 if (mDebugRegion > 1) {
1540 usleep(mDebugRegion * 1000);
1541 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001542
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001543 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001544 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001545 continue;
1546 }
1547
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001548 status_t result = display->prepareFrame(*getBE().mHwc);
1549 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
1550 display->getHwcDisplayId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001551 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001552}
1553
Adrian Roos1e1a1282017-11-01 19:05:31 +01001554void SurfaceFlinger::doTracing(const char* where) {
1555 ATRACE_CALL();
1556 ATRACE_NAME(where);
1557 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001558 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001559 }
1560}
1561
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001562void SurfaceFlinger::logLayerStats() {
1563 ATRACE_CALL();
1564 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001565 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001566 if (display->isPrimary()) {
1567 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001568 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001569 }
1570 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001571
1572 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001573 }
1574}
1575
Chia-I Wu30505fb2018-03-26 16:20:31 -07001576void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001578 ATRACE_CALL();
1579 ALOGV("preComposition");
1580
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001582 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001583 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001584 needExtraInvalidate = true;
1585 }
Robert Carr2047fae2016-11-28 14:09:09 -08001586 });
1587
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588 if (needExtraInvalidate) {
1589 signalLayerUpdate();
1590 }
1591}
1592
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001593void SurfaceFlinger::updateCompositorTiming(
1594 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1595 std::shared_ptr<FenceTime>& presentFenceTime) {
1596 // Update queue of past composite+present times and determine the
1597 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001598 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001599 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001600 while (!getBE().mCompositePresentTimes.empty()) {
1601 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001602 // Cached values should have been updated before calling this method,
1603 // which helps avoid duplicate syscalls.
1604 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1605 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1606 break;
1607 }
1608 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001609 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001610 }
1611
1612 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001613 while (getBE().mCompositePresentTimes.size() > 16) {
1614 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001615 }
1616
Brian Andersond0010582017-03-07 13:20:31 -08001617 setCompositorTimingSnapped(
1618 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1619}
1620
1621void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1622 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001623 // Integer division and modulo round toward 0 not -inf, so we need to
1624 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001625 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001626 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1627 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1628
Brian Andersond0010582017-03-07 13:20:31 -08001629 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1630 if (idealLatency <= 0) {
1631 idealLatency = vsyncInterval;
1632 }
1633
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001634 // Snap the latency to a value that removes scheduling jitter from the
1635 // composition and present times, which often have >1ms of jitter.
1636 // Reducing jitter is important if an app attempts to extrapolate
1637 // something (such as user input) to an accurate diasplay time.
1638 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1639 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001640 nsecs_t bias = vsyncInterval / 2;
1641 int64_t extraVsyncs =
1642 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1643 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1644 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001645
David Sodman99974d22017-11-28 12:04:33 -08001646 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1647 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1648 getBE().mCompositorTiming.interval = vsyncInterval;
1649 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650}
1651
Chia-I Wu30505fb2018-03-26 16:20:31 -07001652void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001653{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001654 ATRACE_CALL();
1655 ALOGV("postComposition");
1656
Brian Anderson3546a3f2016-07-14 11:51:14 -07001657 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001658 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001659 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001660 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001661 }
1662
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001663 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001664 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001665
David Sodman73beded2017-11-15 11:56:06 -08001666 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001667 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001668 if (display && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001669 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001670 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001671 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001672 } else {
1673 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1674 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001675
David Sodman73beded2017-11-15 11:56:06 -08001676 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001677 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001678 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001679 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001680
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001681 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1682 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1683
Chia-I Wu30505fb2018-03-26 16:20:31 -07001684 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001685 // when we started doing work for this frame, but that should be okay
1686 // since updateCompositorTiming has snapping logic.
1687 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001688 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001689 CompositorTiming compositorTiming;
1690 {
David Sodman99974d22017-11-28 12:04:33 -08001691 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1692 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001693 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001694
Robert Carr2047fae2016-11-28 14:09:09 -08001695 mDrawingState.traverseInZOrder([&](Layer* layer) {
1696 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001697 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001698 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001699 recordBufferingStats(layer->getName().string(),
1700 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001701 }
Robert Carr2047fae2016-11-28 14:09:09 -08001702 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001703
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001704 if (presentFenceTime->isValid()) {
1705 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001706 enableHardwareVsync();
1707 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001708 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001709 }
1710 }
1711
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001712 if (!hasSyncFramework) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001713 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001714 enableHardwareVsync();
1715 }
1716 }
1717
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001718 if (mAnimCompositionPending) {
1719 mAnimCompositionPending = false;
1720
Brian Anderson4e606e32017-03-16 15:34:57 -07001721 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001722 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001723 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001724 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001725 // The HWC doesn't support present fences, so use the refresh
1726 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001727 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001728 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001729 mAnimFrameTracker.setActualPresentTime(presentTime);
1730 }
1731 mAnimFrameTracker.advanceFrame();
1732 }
Dan Stozab90cf072015-03-05 11:05:59 -08001733
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001734 mTimeStats.incrementTotalFrames();
1735 if (mHadClientComposition) {
1736 mTimeStats.incrementClientCompositionFrames();
1737 }
1738
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001739 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001740 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001741 return;
1742 }
1743
1744 nsecs_t currentTime = systemTime();
1745 if (mHasPoweredOff) {
1746 mHasPoweredOff = false;
1747 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001748 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001749 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001750 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1751 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001752 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001753 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001754 }
David Sodman4a36e932017-11-07 14:29:47 -08001755 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001756 }
David Sodman4a36e932017-11-07 14:29:47 -08001757 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001758}
1759
1760void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001761 ATRACE_CALL();
1762 ALOGV("rebuildLayerStacks");
1763
Mathias Agopiancd60f992012-08-16 16:28:27 -07001764 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001765 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001766 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001767 mVisibleRegionsDirty = false;
1768 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001769
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001770 for (const auto& pair : mDisplays) {
1771 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001772 Region opaqueRegion;
1773 Region dirtyRegion;
1774 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001775 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001776 const Transform& tr = display->getTransform();
1777 const Rect bounds = display->getBounds();
1778 if (display->isPoweredOn()) {
1779 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001780
Jeff Sharkey76488112017-02-27 14:15:18 -07001781 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001782 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001783 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001784 Region drawRegion(tr.transform(
1785 layer->visibleNonTransparentRegion));
1786 drawRegion.andSelf(bounds);
1787 if (!drawRegion.isEmpty()) {
1788 layersSortedByZ.add(layer);
1789 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001790 // Clear out the HWC layer if this layer was
1791 // previously visible, but no longer is
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001792 hwcLayerDestroyed = layer->destroyHwcLayer(display->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001793 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001794 } else {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001795 // WM changes display->layerStack upon sleep/awake.
Chia-I Wu30505fb2018-03-26 16:20:31 -07001796 // Here we make sure we delete the HWC layers even if
1797 // WM changed their layer stack.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001798 hwcLayerDestroyed = layer->destroyHwcLayer(display->getHwcDisplayId());
Chia-I Wu83806892017-11-16 10:50:20 -08001799 }
1800
1801 // If a layer is not going to get a release fence because
1802 // it is invisible, but it is also going to release its
1803 // old buffer, add it to the list of layers needing
1804 // fences.
1805 if (hwcLayerDestroyed) {
1806 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1807 mLayersWithQueuedFrames.cend(), layer);
1808 if (found != mLayersWithQueuedFrames.cend()) {
1809 layersNeedingFences.add(layer);
1810 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001811 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001812 });
1813 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001814 display->setVisibleLayersSortedByZ(layersSortedByZ);
1815 display->setLayersNeedingFences(layersNeedingFences);
1816 display->undefinedRegion.set(bounds);
1817 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1818 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001819 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001820 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001821}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001822
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001823// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001824// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001825// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001826// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001827// The returned HDR data space is one of
1828// - Dataspace::UNKNOWN
1829// - Dataspace::BT2020_HLG
1830// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001831Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1832 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001833 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001834 *outHdrDataSpace = Dataspace::UNKNOWN;
1835
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001836 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001837 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001838 case Dataspace::V0_SCRGB:
1839 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001840 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001841 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001842 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001843 case Dataspace::BT2020_PQ:
1844 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001845 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001846 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001847 case Dataspace::BT2020_HLG:
1848 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001849 // When there's mixed PQ content and HLG content, we set the HDR
1850 // data space to be BT2020_PQ and convert HLG to PQ.
1851 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1852 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001853 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001854 break;
1855 default:
1856 break;
1857 }
Romain Guy54f154a2017-10-24 21:40:32 +01001858 }
1859
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001860 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001861}
1862
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001863// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001864void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1865 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001866 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1867 *outMode = ColorMode::NATIVE;
1868 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001869 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001870 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001871 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001872
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001873 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001874 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001875
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001876 // respect hdrDataSpace only when there is modern HDR support
1877 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001878 display->hasModernHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001879 if (isHdr) {
1880 bestDataSpace = hdrDataSpace;
1881 }
1882
Chia-I Wu0d711262018-05-21 15:19:35 -07001883 RenderIntent intent;
1884 switch (mDisplayColorSetting) {
1885 case DisplayColorSetting::MANAGED:
1886 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001887 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001888 break;
1889 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001890 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001891 break;
1892 default: // vendor display color setting
1893 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1894 break;
1895 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001896
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001897 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001898}
1899
Chia-I Wu30505fb2018-03-26 16:20:31 -07001900void SurfaceFlinger::setUpHWComposer() {
1901 ATRACE_CALL();
1902 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001903
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001904 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001905 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
1906 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1907 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07001908
1909 // If nothing has changed (!dirty), don't recompose.
1910 // If something changed, but we don't currently have any visible layers,
1911 // and didn't when we last did a composition, then skip it this time.
1912 // The second rule does two things:
1913 // - When all layers are removed from a display, we'll emit one black
1914 // frame, then nothing more until we get new layers.
1915 // - When a display is created with a private layer stack, we won't
1916 // emit any black frames until a layer is added to the layer stack.
1917 bool mustRecompose = dirty && !(empty && wasEmpty);
1918
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001919 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
1920 display->getHwcDisplayId(), mustRecompose ? "doing" : "skipping",
1921 dirty ? "+" : "-", empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07001922
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001923 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001924
1925 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001926 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07001927 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001928 }
1929
Chia-I Wu30505fb2018-03-26 16:20:31 -07001930 // build the h/w work list
1931 if (CC_UNLIKELY(mGeometryInvalid)) {
1932 mGeometryInvalid = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001933 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001934 const auto hwcId = display->getHwcDisplayId();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001935 if (hwcId >= 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001936 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001937 for (size_t i = 0; i < currentLayers.size(); i++) {
1938 const auto& layer = currentLayers[i];
1939 if (!layer->hasHwcLayer(hwcId)) {
1940 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
1941 layer->forceClientComposition(hwcId);
1942 continue;
1943 }
1944 }
1945
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001946 layer->setGeometry(display, i);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001947 if (mDebugDisableHWC || mDebugRegion) {
1948 layer->forceClientComposition(hwcId);
1949 }
1950 }
1951 }
1952 }
1953 }
1954
Chia-I Wu30505fb2018-03-26 16:20:31 -07001955 // Set the per-frame data
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001956 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001957 const auto hwcId = display->getHwcDisplayId();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001958
1959 if (hwcId < 0) {
1960 continue;
1961 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07001962 if (mDrawingState.colorMatrixChanged) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001963 display->setColorTransform(mDrawingState.colorMatrix);
Chia-I Wu28f320b2018-05-03 11:02:56 -07001964 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001965 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
1966 display->getHwcDisplayId(), result);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001967 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001968 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001969 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1970 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001971 !display->hasHDR10Support()) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001972 layer->forceClientComposition(hwcId);
1973 }
Chia-I Wu01591c92018-05-22 12:03:00 -07001974 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1975 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001976 !display->hasHLGSupport()) {
Peiyong Linf59a7192018-04-25 11:19:31 -07001977 layer->forceClientComposition(hwcId);
1978 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001979
1980 if (layer->getForceClientComposition(hwcId)) {
1981 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1982 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1983 continue;
1984 }
1985
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001986 layer->setPerFrameData(display);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001987 }
1988
1989 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001990 ColorMode colorMode;
1991 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001992 RenderIntent renderIntent;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001993 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1994 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001995 }
1996 }
1997
Chia-I Wu28f320b2018-05-03 11:02:56 -07001998 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07001999
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002000 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002001 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002002 continue;
2003 }
2004
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002005 status_t result = display->prepareFrame(*getBE().mHwc);
2006 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
2007 display->getHwcDisplayId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002008 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002009}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002010
Mathias Agopiancd60f992012-08-16 16:28:27 -07002011void SurfaceFlinger::doComposition() {
2012 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002013 ALOGV("doComposition");
2014
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002015 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002016 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002017 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002018 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002019 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002020
2021 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002022 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002024 display->dirtyRegion.clear();
2025 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002026 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002027 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002028 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002029}
2030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002031void SurfaceFlinger::postFramebuffer()
2032{
Mathias Agopian841cde52012-03-01 15:44:37 -08002033 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002034 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002035
Mathias Agopiana44b0412011-10-16 18:46:35 -07002036 const nsecs_t now = systemTime();
2037 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002038
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002039 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002040 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002041 continue;
2042 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002043 const auto hwcId = display->getHwcDisplayId();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002044 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002045 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002046 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002047 display->onSwapBuffersCompleted();
2048 display->makeCurrent();
2049 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002050 // The layer buffer from the previous frame (if any) is released
2051 // by HWC only when the release fence from this frame (if any) is
2052 // signaled. Always get the release fence from HWC first.
2053 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002054 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002055
2056 // If the layer was client composited in the previous frame, we
2057 // need to merge with the previous client target acquire fence.
2058 // Since we do not track that, always merge with the current
2059 // client target acquire fence when it is available, even though
2060 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002061 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002062 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002063 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002064 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002065
David Sodmanb8af7922017-12-21 15:17:55 -08002066 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 }
Chia-I Wu83806892017-11-16 10:50:20 -08002068
2069 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002070 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002071 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002072 if (!display->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002073 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002074 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002075 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002076 }
2077 }
2078
Dan Stoza9e56aa02015-11-02 13:00:03 -08002079 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002080 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002081 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002082 }
2083
Mathias Agopiana44b0412011-10-16 18:46:35 -07002084 mLastSwapBufferTime = systemTime() - now;
2085 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002086
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002087 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002088 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2089 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2090 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2091 logFrameStats();
2092 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002093 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002094}
2095
Mathias Agopian87baae12012-07-31 12:38:26 -07002096void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002097{
Mathias Agopian841cde52012-03-01 15:44:37 -08002098 ATRACE_CALL();
2099
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002100 // here we keep a copy of the drawing state (that is the state that's
2101 // going to be overwritten by handleTransactionLocked()) outside of
2102 // mStateLock so that the side-effects of the State assignment
2103 // don't happen with mStateLock held (which can cause deadlocks).
2104 State drawingState(mDrawingState);
2105
Mathias Agopianca4d3602011-05-19 15:38:14 -07002106 Mutex::Autolock _l(mStateLock);
2107 const nsecs_t now = systemTime();
2108 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002109
Mathias Agopianca4d3602011-05-19 15:38:14 -07002110 // Here we're guaranteed that some transaction flags are set
2111 // so we can call handleTransactionLocked() unconditionally.
2112 // We call getTransactionFlags(), which will also clear the flags,
2113 // with mStateLock held to guarantee that mCurrentState won't change
2114 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002115
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002116 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002117 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002118 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002119
Mathias Agopianca4d3602011-05-19 15:38:14 -07002120 mLastTransactionTime = systemTime() - now;
2121 mDebugInTransaction = 0;
2122 invalidateHwcGeometry();
2123 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002124}
2125
Lloyd Pique715a2c12017-12-14 17:18:08 -08002126DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002127 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002128 // Figure out whether the event is for the primary display or an
2129 // external display by matching the Hwc display id against one for a
2130 // connected display. If we did not find a match, we then check what
2131 // displays are not already connected to determine the type. If we don't
2132 // have a connected primary display, we assume the new display is meant to
2133 // be the primary display, and then if we don't have an external display,
2134 // we assume it is that.
2135 const auto primaryDisplayId =
2136 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2137 const auto externalDisplayId =
2138 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2139 if (primaryDisplayId && primaryDisplayId == display) {
2140 return DisplayDevice::DISPLAY_PRIMARY;
2141 } else if (externalDisplayId && externalDisplayId == display) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002142 return DisplayDevice::DISPLAY_EXTERNAL;
Lloyd Pique715a2c12017-12-14 17:18:08 -08002143 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2144 return DisplayDevice::DISPLAY_PRIMARY;
2145 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2146 return DisplayDevice::DISPLAY_EXTERNAL;
2147 }
2148
2149 return DisplayDevice::DISPLAY_ID_INVALID;
2150}
2151
Lloyd Piqueba04e622017-12-14 17:11:26 -08002152void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2153 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002154 auto displayType = determineDisplayType(event.display, event.connection);
2155 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2156 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2157 continue;
2158 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002159
2160 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2161 ALOGE("External displays are not supported by the vr hardware composer.");
2162 continue;
2163 }
2164
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002165 const auto displayId =
2166 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
2167 if (displayId) {
2168 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.display, *displayId);
2169 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002170
2171 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002172 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002173 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002174 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002175 DisplayDeviceState info;
2176 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002177 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2178 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002179 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002180 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002181 mInterceptor->saveDisplayCreation(info);
2182 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002183 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002184 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002185
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002186 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002187 if (idx >= 0) {
2188 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002189 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002190 mCurrentState.displays.removeItemsAt(idx);
2191 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002192 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002193 }
2194
2195 processDisplayChangesLocked();
2196 }
2197
2198 mPendingHotplugEvents.clear();
2199}
2200
Lloyd Pique99d3da52018-01-22 17:48:03 -08002201sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002202 const wp<IBinder>& displayToken, int hwcId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002203 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002204 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002205 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002206
Lloyd Pique99d3da52018-01-22 17:48:03 -08002207 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002208 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002209 for (ColorMode colorMode : modes) {
2210 switch (colorMode) {
2211 case ColorMode::DISPLAY_P3:
2212 case ColorMode::ADOBE_RGB:
2213 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002214 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002215 break;
2216 default:
2217 break;
2218 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002219
2220 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2221 colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002222 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002223 }
2224 }
2225
Peiyong Lin62665892018-04-16 11:07:44 -07002226 HdrCapabilities hdrCapabilities;
2227 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002228
2229 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2230 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2231
2232 /*
2233 * Create our display's surface
2234 */
2235 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2236 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002237 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002238 renderSurface->setNativeWindow(nativeWindow.get());
2239 const int displayWidth = renderSurface->queryWidth();
2240 const int displayHeight = renderSurface->queryHeight();
2241
2242 // Make sure that composition can never be stalled by a virtual display
2243 // consumer that isn't processing buffers fast enough. We have to do this
2244 // in two places:
2245 // * Here, in case the display is composed entirely by HWC.
2246 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2247 // window's swap interval in eglMakeCurrent, so they'll override the
2248 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002249 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002250 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2251 }
2252
2253 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002254 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002255
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002256 sp<DisplayDevice> display =
2257 new DisplayDevice(this, state.type, hwcId, state.isSecure, displayToken, nativeWindow,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002258 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin0ac5f4e2018-04-19 22:06:34 -07002259 hasWideColorGamut, hdrCapabilities,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002260 getHwComposer().getSupportedPerFrameMetadata(hwcId), hwcColorModes,
2261 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002262
2263 if (maxFrameBufferAcquiredBuffers >= 3) {
2264 nativeWindowSurface->preallocateBuffers();
2265 }
2266
2267 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002268 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2269 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002270 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002271 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002272 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002273 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002274 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002275 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002276 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002277 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002278 display->setLayerStack(state.layerStack);
2279 display->setProjection(state.orientation, state.viewport, state.frame);
2280 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002281
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002282 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002283}
2284
Lloyd Pique347200f2017-12-14 17:00:15 -08002285void SurfaceFlinger::processDisplayChangesLocked() {
2286 // here we take advantage of Vector's copy-on-write semantics to
2287 // improve performance by skipping the transaction entirely when
2288 // know that the lists are identical
2289 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2290 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2291 if (!curr.isIdenticalTo(draw)) {
2292 mVisibleRegionsDirty = true;
2293 const size_t cc = curr.size();
2294 size_t dc = draw.size();
2295
2296 // find the displays that were removed
2297 // (ie: in drawing state but not in current state)
2298 // also handle displays that changed
2299 // (ie: displays that are in both lists)
2300 for (size_t i = 0; i < dc;) {
2301 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2302 if (j < 0) {
2303 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002304 // Call makeCurrent() on the primary display so we can
2305 // be sure that nothing associated with this display
2306 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002307 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2308 defaultDisplay->makeCurrent();
2309 }
2310 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2311 display->disconnect(getHwComposer());
2312 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002313 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2314 mEventThread->onHotplugReceived(draw[i].type, false);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002315 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002316 } else {
2317 // this display is in both lists. see if something changed.
2318 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002319 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002320 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2321 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2322 if (state_binder != draw_binder) {
2323 // changing the surface is like destroying and
2324 // recreating the DisplayDevice, so we just remove it
2325 // from the drawing state, so that it get re-added
2326 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002327 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2328 display->disconnect(getHwComposer());
2329 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002330 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002331 mDrawingState.displays.removeItemsAt(i);
2332 dc--;
2333 // at this point we must loop to the next item
2334 continue;
2335 }
2336
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002337 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002338 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002339 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002340 }
2341 if ((state.orientation != draw[i].orientation) ||
2342 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002343 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002344 }
2345 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002346 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002347 }
2348 }
2349 }
2350 ++i;
2351 }
2352
2353 // find displays that were added
2354 // (ie: in current state but not in drawing state)
2355 for (size_t i = 0; i < cc; i++) {
2356 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2357 const DisplayDeviceState& state(curr[i]);
2358
2359 sp<DisplaySurface> dispSurface;
2360 sp<IGraphicBufferProducer> producer;
2361 sp<IGraphicBufferProducer> bqProducer;
2362 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002363 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002364
2365 int32_t hwcId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002366 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002367 // Virtual displays without a surface are dormant:
2368 // they have external state (layer stack, projection,
2369 // etc.) but no internal state (i.e. a DisplayDevice).
2370 if (state.surface != nullptr) {
2371 // Allow VR composer to use virtual displays.
2372 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2373 int width = 0;
2374 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2375 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2376 int height = 0;
2377 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2378 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2379 int intFormat = 0;
2380 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2381 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002382 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002383
2384 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2385 }
2386
2387 // TODO: Plumb requested format back up to consumer
2388
2389 sp<VirtualDisplaySurface> vds =
2390 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2391 bqProducer, bqConsumer,
2392 state.displayName);
2393
2394 dispSurface = vds;
2395 producer = vds;
2396 }
2397 } else {
2398 ALOGE_IF(state.surface != nullptr,
2399 "adding a supported display, but rendering "
2400 "surface is provided (%p), ignoring it",
2401 state.surface.get());
2402
2403 hwcId = state.type;
2404 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2405 producer = bqProducer;
2406 }
2407
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002408 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002409 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002410 mDisplays.emplace(displayToken,
2411 setupNewDisplayDeviceInternal(displayToken, hwcId, state,
2412 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002413 if (!state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002414 mEventThread->onHotplugReceived(state.type, true);
2415 }
2416 }
2417 }
2418 }
2419 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002420
2421 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002422}
2423
Mathias Agopian87baae12012-07-31 12:38:26 -07002424void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002425{
Dan Stoza7dde5992015-05-22 09:51:44 -07002426 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002427 mCurrentState.traverseInZOrder([](Layer* layer) {
2428 layer->notifyAvailableFrames();
2429 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002430
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002431 /*
2432 * Traversal of the children
2433 * (perform the transaction for each of them if needed)
2434 */
2435
Mathias Agopian3559b072012-08-15 13:46:03 -07002436 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002437 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002438 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002439 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002440
2441 const uint32_t flags = layer->doTransaction(0);
2442 if (flags & Layer::eVisibleRegion)
2443 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002444 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445 }
2446
2447 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002448 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002449 */
2450
Mathias Agopiane57f2922012-08-09 16:29:12 -07002451 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002452 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002453 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002454 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002456 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002457 // The transform hint might have changed for some layers
2458 // (either because a display has changed, or because a layer
2459 // as changed).
2460 //
2461 // Walk through all the layers in currentLayers,
2462 // and update their transform hint.
2463 //
2464 // If a layer is visible only on a single display, then that
2465 // display is used to calculate the hint, otherwise we use the
2466 // default display.
2467 //
2468 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2469 // the hint is set before we acquire a buffer from the surface texture.
2470 //
2471 // NOTE: layer transactions have taken place already, so we use their
2472 // drawing state. However, SurfaceFlinger's own transaction has not
2473 // happened yet, so we must use the current state layer list
2474 // (soon to become the drawing state list).
2475 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002476 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002477 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002478 bool first = true;
2479 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002480 // NOTE: we rely on the fact that layers are sorted by
2481 // layerStack first (so we don't have to traverse the list
2482 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002483 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002484 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002485 currentlayerStack = layerStack;
2486 // figure out if this layerstack is mirrored
2487 // (more than one display) if so, pick the default display,
2488 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002489 hintDisplay = nullptr;
2490 for (const auto& [token, display] : mDisplays) {
2491 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2492 if (hintDisplay) {
2493 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002494 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002495 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002496 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002497 }
2498 }
2499 }
2500 }
Chet Haase91d25932013-04-11 15:24:55 -07002501
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002502 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002503 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2504 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002505
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002506 // could be null when this layer is using a layerStack
2507 // that is not visible on any display. Also can occur at
2508 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002509 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002510 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002511
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002512 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002513 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002514 if (hintDisplay) {
2515 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002516 }
Robert Carr2047fae2016-11-28 14:09:09 -08002517
2518 first = false;
2519 });
Mathias Agopian84300952012-11-21 16:02:13 -08002520 }
2521
2522
Mathias Agopian3559b072012-08-15 13:46:03 -07002523 /*
2524 * Perform our own transaction if needed
2525 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002526
2527 if (mLayersAdded) {
2528 mLayersAdded = false;
2529 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002530 mVisibleRegionsDirty = true;
2531 }
2532
2533 // some layers might have been removed, so
2534 // we need to update the regions they're exposing.
2535 if (mLayersRemoved) {
2536 mLayersRemoved = false;
2537 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002538 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002539 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002540 // this layer is not visible anymore
2541 // TODO: we could traverse the tree from front to back and
2542 // compute the actual visible region
2543 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002544 Region visibleReg;
2545 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002546 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002547 }
Robert Carr2047fae2016-11-28 14:09:09 -08002548 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002549 }
2550
2551 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002552
2553 updateCursorAsync();
2554}
2555
2556void SurfaceFlinger::updateCursorAsync()
2557{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002558 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002559 if (display->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002560 continue;
2561 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002562
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002563 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2564 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002565 }
2566 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002567}
2568
2569void SurfaceFlinger::commitTransaction()
2570{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002571 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002572 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002573 for (const auto& l : mLayersPendingRemoval) {
2574 recordBufferingStats(l->getName().string(),
2575 l->getOccupancyHistory(true));
2576 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002577 }
2578 mLayersPendingRemoval.clear();
2579 }
2580
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002581 // If this transaction is part of a window animation then the next frame
2582 // we composite should be considered an animation as well.
2583 mAnimCompositionPending = mAnimTransactionPending;
2584
Mathias Agopian4fec8732012-06-29 14:12:52 -07002585 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002586 // clear the "changed" flags in current state
2587 mCurrentState.colorMatrixChanged = false;
2588
Robert Carr1f0a16a2016-10-24 16:27:39 -07002589 mDrawingState.traverseInZOrder([](Layer* layer) {
2590 layer->commitChildList();
2591 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002592 mTransactionPending = false;
2593 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002594 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595}
2596
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002597void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2598 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002599 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002600 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002601
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602 Region aboveOpaqueLayers;
2603 Region aboveCoveredLayers;
2604 Region dirty;
2605
Mathias Agopian87baae12012-07-31 12:38:26 -07002606 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607
Robert Carr2047fae2016-11-28 14:09:09 -08002608 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002609 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002610 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002611
Jesse Hall01e29052013-02-19 16:13:35 -08002612 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002613 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002614 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002615 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002616
Mathias Agopianab028732010-03-16 16:41:46 -07002617 /*
2618 * opaqueRegion: area of a surface that is fully opaque.
2619 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002621
2622 /*
2623 * visibleRegion: area of a surface that is visible on screen
2624 * and not fully transparent. This is essentially the layer's
2625 * footprint minus the opaque regions above it.
2626 * Areas covered by a translucent surface are considered visible.
2627 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002629
2630 /*
2631 * coveredRegion: area of a surface that is covered by all
2632 * visible regions above it (which includes the translucent areas).
2633 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002635
Jesse Halla8026d22012-09-25 13:25:04 -07002636 /*
2637 * transparentRegion: area of a surface that is hinted to be completely
2638 * transparent. This is only used to tell when the layer has no visible
2639 * non-transparent regions and can be removed from the layer list. It
2640 * does not affect the visibleRegion of this layer or any layers
2641 * beneath it. The hint may not be correct if apps don't respect the
2642 * SurfaceView restrictions (which, sadly, some don't).
2643 */
2644 Region transparentRegion;
2645
Mathias Agopianab028732010-03-16 16:41:46 -07002646
2647 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002648 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002649 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002650 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002652 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002653 if (!visibleRegion.isEmpty()) {
2654 // Remove the transparent area from the visible region
2655 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002656 if (tr.preserveRects()) {
2657 // transform the transparent region
2658 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002659 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002660 // transformation too complex, can't do the
2661 // transparent region optimization.
2662 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002663 }
Mathias Agopianab028732010-03-16 16:41:46 -07002664 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665
Mathias Agopianab028732010-03-16 16:41:46 -07002666 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002667 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002668 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002669 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2670 // the opaque region is the layer's footprint
2671 opaqueRegion = visibleRegion;
2672 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002673 }
2674 }
2675
Robert Carre5f4f692018-01-12 13:12:28 -08002676 if (visibleRegion.isEmpty()) {
2677 layer->clearVisibilityRegions();
2678 return;
2679 }
2680
Mathias Agopianab028732010-03-16 16:41:46 -07002681 // Clip the covered region to the visible region
2682 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2683
2684 // Update aboveCoveredLayers for next (lower) layer
2685 aboveCoveredLayers.orSelf(visibleRegion);
2686
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687 // subtract the opaque region covered by the layers above us
2688 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002689
2690 // compute this layer's dirty region
2691 if (layer->contentDirty) {
2692 // we need to invalidate the whole region
2693 dirty = visibleRegion;
2694 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002695 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002696 layer->contentDirty = false;
2697 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002698 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002699 * the exposed region consists of two components:
2700 * 1) what's VISIBLE now and was COVERED before
2701 * 2) what's EXPOSED now less what was EXPOSED before
2702 *
2703 * note that (1) is conservative, we start with the whole
2704 * visible region but only keep what used to be covered by
2705 * something -- which mean it may have been exposed.
2706 *
2707 * (2) handles areas that were not covered by anything but got
2708 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002709 */
Mathias Agopianab028732010-03-16 16:41:46 -07002710 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002711 const Region oldVisibleRegion = layer->visibleRegion;
2712 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002713 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2714 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 }
2716 dirty.subtractSelf(aboveOpaqueLayers);
2717
2718 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002719 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002720
Mathias Agopianab028732010-03-16 16:41:46 -07002721 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002722 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002723
Jesse Halla8026d22012-09-25 13:25:04 -07002724 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725 layer->setVisibleRegion(visibleRegion);
2726 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002727 layer->setVisibleNonTransparentRegion(
2728 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002729 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730
Mathias Agopian87baae12012-07-31 12:38:26 -07002731 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002732}
2733
Chia-I Wuab0c3192017-08-01 11:29:00 -07002734void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002735 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002736 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2737 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002738 }
2739 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002740}
2741
Dan Stoza6b9454d2014-11-07 16:00:59 -08002742bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002744 ALOGV("handlePageFlip");
2745
Brian Andersond6927fb2016-07-23 23:37:30 -07002746 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747
Mathias Agopian4fec8732012-06-29 14:12:52 -07002748 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002749 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002750 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002751
2752 // Store the set of layers that need updates. This set must not change as
2753 // buffers are being latched, as this could result in a deadlock.
2754 // Example: Two producers share the same command stream and:
2755 // 1.) Layer 0 is latched
2756 // 2.) Layer 0 gets a new frame
2757 // 2.) Layer 1 gets a new frame
2758 // 3.) Layer 1 is latched.
2759 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2760 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002761 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002762 if (layer->hasQueuedFrame()) {
2763 frameQueued = true;
2764 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002765 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002766 } else {
2767 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002768 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002769 } else {
2770 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002771 }
Robert Carr2047fae2016-11-28 14:09:09 -08002772 });
2773
Dan Stoza9e56aa02015-11-02 13:00:03 -08002774 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002775 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002776 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002777 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002778 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002779 newDataLatched = true;
2780 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002781 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002782
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002783 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002784
2785 // If we will need to wake up at some time in the future to deal with a
2786 // queued frame that shouldn't be displayed during this vsync period, wake
2787 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002788 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002789 signalLayerUpdate();
2790 }
2791
2792 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002793 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794}
2795
Mathias Agopianad456f92011-01-13 17:53:01 -08002796void SurfaceFlinger::invalidateHwcGeometry()
2797{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002798 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002799}
2800
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002801void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2802 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002803 // We only need to actually compose the display if:
2804 // 1) It is being handled by hardware composer, which may need this to
2805 // keep its virtual display state machine in sync, or
2806 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002807 bool isHwcDisplay = display->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002808 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002809 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002810 return;
2811 }
2812
Dan Stoza9e56aa02015-11-02 13:00:03 -08002813 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002814 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002815
2816 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002817 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818}
2819
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002820bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002821 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002822
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002823 const Region bounds(display->bounds());
2824 const DisplayRenderArea renderArea(display);
2825 const auto hwcId = display->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002826 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002827 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002828
Chia-I Wu8e50e692018-05-04 10:12:37 -07002829 bool applyColorMatrix = false;
Peiyong Lin00f9c022018-05-09 15:35:33 -07002830 bool needsLegacyColorMatrix = false;
2831 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002832
Dan Stoza9e56aa02015-11-02 13:00:03 -08002833 if (hasClientComposition) {
2834 ALOGV("hasClientComposition");
2835
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002836 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002837 if (display->hasWideColorGamut()) {
2838 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002839 }
2840 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002841 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002842 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002843
Chia-I Wu8e50e692018-05-04 10:12:37 -07002844 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2845 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2846 HWC2::Capability::SkipClientColorTransform);
2847
2848 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2849 if (applyColorMatrix) {
Peiyong Lin00f9c022018-05-09 15:35:33 -07002850 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002851 }
2852
Chia-I Wubbb44462018-05-21 15:33:27 -07002853 needsLegacyColorMatrix =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002854 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2855 outputDataspace != Dataspace::UNKNOWN && outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002856
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002857 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002858 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002859 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002860 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002861
2862 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002863 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002864 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2865 }
2866 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002867 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002868
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002869 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002870 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002871 // when using overlays, we assume a fully transparent framebuffer
2872 // NOTE: we could reduce how much we need to clear, for instance
2873 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002874 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002875 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002876 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002877 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002878 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002879 // we're left with the letterbox region
2880 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002881 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002882
2883 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002884 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002885
Mathias Agopianb9494d52012-04-18 02:28:45 -07002886 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002887 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002888 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002889 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002890 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002891 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002892
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002893 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002894 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002895 // scissor on the main display. It should never be needed
2896 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002897 const Rect& bounds = display->getBounds();
2898 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002899 if (scissor != bounds) {
2900 // scissor doesn't match the screen's dimensions, so we
2901 // need to clear everything outside of it and enable
2902 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002903
Mathias Agopianf45c5102012-10-24 16:29:17 -07002904 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002905 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002906 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002907 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002908 }
2909 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002910 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002911
Mathias Agopian85d751c2012-08-29 16:59:24 -07002912 /*
2913 * and then, render the layers targeted at the framebuffer
2914 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002915
Dan Stoza9e56aa02015-11-02 13:00:03 -08002916 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002917 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002918 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002919 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002920 const Region clip(bounds.intersect(
2921 displayTransform.transform(layer->visibleRegion)));
2922 ALOGV("Layer: %s", layer->getName().string());
2923 ALOGV(" Composition type: %s",
2924 to_string(layer->getCompositionType(hwcId)).c_str());
2925 if (!clip.isEmpty()) {
2926 switch (layer->getCompositionType(hwcId)) {
2927 case HWC2::Composition::Cursor:
2928 case HWC2::Composition::Device:
2929 case HWC2::Composition::Sideband:
2930 case HWC2::Composition::SolidColor: {
2931 const Layer::State& state(layer->getDrawingState());
2932 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2933 layer->isOpaque(state) && (state.color.a == 1.0f)
2934 && hasClientComposition) {
2935 // never clear the very first layer since we're
2936 // guaranteed the FB is already cleared
2937 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002938 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002939 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002940 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002941 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002942 // switch color matrices lazily
Peiyong Lin00f9c022018-05-09 15:35:33 -07002943 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
2944 if (!legacyColorMatrixApplied) {
2945 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
2946 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002947 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07002948 } else if (legacyColorMatrixApplied) {
2949 getRenderEngine().setSaturationMatrix(mat4());
2950 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002951 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07002952
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002953 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002954 break;
2955 }
2956 default:
2957 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002958 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002959 } else {
2960 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002961 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002962 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002963 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002964
Peiyong Lin00f9c022018-05-09 15:35:33 -07002965 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002966 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002967 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07002968 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
2969 getRenderEngine().setSaturationMatrix(mat4());
2970 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002971
Mathias Agopianf45c5102012-10-24 16:29:17 -07002972 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002973 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002974 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002975}
2976
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002977void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2978 const Region& region) const {
2979 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002980 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002981 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982}
2983
Dan Stoza7d89d062015-04-30 13:29:25 -07002984status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002985 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002986 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002987 const sp<Layer>& lbc,
2988 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002989{
Dan Stoza7d89d062015-04-30 13:29:25 -07002990 // add this layer to the current state list
2991 {
2992 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002993 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002994 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2995 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002996 return NO_MEMORY;
2997 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002998 if (parent == nullptr) {
2999 mCurrentState.layersSortedByZ.add(lbc);
3000 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003001 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003002 ALOGE("addClientLayer called with a removed parent");
3003 return NAME_NOT_FOUND;
3004 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003005 parent->addChild(lbc);
3006 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003007
Yiwei Zhang243b3782018-05-15 17:40:04 -07003008 if (gbc != nullptr) {
3009 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3010 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3011 mMaxGraphicBufferProducerListSize,
3012 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3013 mGraphicBufferProducerList.size(),
3014 mMaxGraphicBufferProducerListSize, mNumLayers);
3015 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003016 mLayersAdded = true;
3017 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003018 }
3019
Mathias Agopian96f08192010-06-02 23:28:45 -07003020 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003021 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003022
Dan Stoza7d89d062015-04-30 13:29:25 -07003023 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003024}
3025
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003026status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003027 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003028 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3029}
Robert Carr7f9b8992017-03-10 11:08:39 -08003030
chaviwca27f252018-02-06 16:46:39 -08003031status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3032 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003033 if (layer->isPendingRemoval()) {
3034 return NO_ERROR;
3035 }
3036
Robert Carr1f0a16a2016-10-24 16:27:39 -07003037 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003038 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003039 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003040 if (topLevelOnly) {
3041 return NO_ERROR;
3042 }
3043
Chia-I Wu98f1c102017-05-30 14:54:08 -07003044 sp<Layer> ancestor = p;
3045 while (ancestor->getParent() != nullptr) {
3046 ancestor = ancestor->getParent();
3047 }
3048 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3049 ALOGE("removeLayer called with a layer whose parent has been removed");
3050 return NAME_NOT_FOUND;
3051 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003052
3053 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003054 } else {
3055 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003056 }
3057
Robert Carr136e2f62017-02-08 17:54:29 -08003058 // As a matter of normal operation, the LayerCleaner will produce a second
3059 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3060 // so we will succeed in promoting it, but it's already been removed
3061 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3062 // otherwise something has gone wrong and we are leaking the layer.
3063 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003064 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3065 layer->getName().string(),
3066 (p != nullptr) ? p->getName().string() : "no-parent");
3067 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003068 } else if (index < 0) {
3069 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003070 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003071
Chia-I Wuc6657022017-08-15 11:18:17 -07003072 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003073 mLayersPendingRemoval.add(layer);
3074 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003075 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003076 setTransactionFlags(eTransactionNeeded);
3077 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003078}
3079
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003080uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003081 return android_atomic_release_load(&mTransactionFlags);
3082}
3083
Mathias Agopian3f844832013-08-07 21:24:32 -07003084uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003085 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3086}
3087
Mathias Agopian3f844832013-08-07 21:24:32 -07003088uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003089 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3090}
3091
3092uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3093 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003094 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003095 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003097 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098 }
3099 return old;
3100}
3101
chaviwca27f252018-02-06 16:46:39 -08003102bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3103 for (const ComposerState& state : states) {
3104 // Here we need to check that the interface we're given is indeed
3105 // one of our own. A malicious client could give us a nullptr
3106 // IInterface, or one of its own or even one of our own but a
3107 // different type. All these situations would cause us to crash.
3108 if (state.client == nullptr) {
3109 return true;
3110 }
3111
3112 sp<IBinder> binder = IInterface::asBinder(state.client);
3113 if (binder == nullptr) {
3114 return true;
3115 }
3116
3117 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3118 return true;
3119 }
3120 }
3121 return false;
3122}
3123
Mathias Agopian8b33f032012-07-24 20:43:54 -07003124void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003125 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003126 const Vector<DisplayState>& displays,
3127 uint32_t flags)
3128{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003129 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003130 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003131 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003132
chaviwca27f252018-02-06 16:46:39 -08003133 if (containsAnyInvalidClientState(states)) {
3134 return;
3135 }
3136
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003137 if (flags & eAnimation) {
3138 // For window updates that are part of an animation we must wait for
3139 // previous animation "frames" to be handled.
3140 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003141 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003142 if (CC_UNLIKELY(err != NO_ERROR)) {
3143 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003144 // caller after a few seconds.
3145 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3146 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003147 mAnimTransactionPending = false;
3148 break;
3149 }
3150 }
3151 }
3152
chaviwca27f252018-02-06 16:46:39 -08003153 for (const DisplayState& display : displays) {
3154 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003155 }
3156
chaviwca27f252018-02-06 16:46:39 -08003157 for (const ComposerState& state : states) {
3158 transactionFlags |= setClientStateLocked(state);
3159 }
3160
3161 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3162 // as destroyed should only occur after setting all other states. This is to allow for a
3163 // child re-parent to happen before marking its original parent as destroyed (which would
3164 // then mark the child as destroyed).
3165 for (const ComposerState& state : states) {
3166 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003167 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003168
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003169 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3170 // anyway. This can be used as a flush mechanism for previous async transactions.
3171 // Empty animation transaction can be used to simulate back-pressure, so also force a
3172 // transaction for empty animation transactions.
3173 if (transactionFlags == 0 &&
3174 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003175 transactionFlags = eTransactionNeeded;
3176 }
3177
Mathias Agopian386aa982011-11-07 21:58:03 -08003178 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003179 if (mInterceptor->isEnabled()) {
3180 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003181 }
Irvel468051e2016-06-13 16:44:44 -07003182
Mathias Agopian386aa982011-11-07 21:58:03 -08003183 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003184 const auto start = (flags & eEarlyWakeup)
3185 ? VSyncModulator::TransactionStart::EARLY
3186 : VSyncModulator::TransactionStart::NORMAL;
3187 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003188
3189 // if this is a synchronous transaction, wait for it to take effect
3190 // before returning.
3191 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003192 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003193 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003194 if (flags & eAnimation) {
3195 mAnimTransactionPending = true;
3196 }
3197 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003198 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3199 if (CC_UNLIKELY(err != NO_ERROR)) {
3200 // just in case something goes wrong in SF, return to the
3201 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003202 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3203 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003204 break;
3205 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003206 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207 }
3208}
3209
Mathias Agopiane57f2922012-08-09 16:29:12 -07003210uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3211{
Jesse Hall9a143922012-10-04 16:29:19 -07003212 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3213 if (dpyIdx < 0)
3214 return 0;
3215
Mathias Agopiane57f2922012-08-09 16:29:12 -07003216 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003217 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003218 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003219 const uint32_t what = s.what;
3220 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003221 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003222 disp.surface = s.surface;
3223 flags |= eDisplayTransactionNeeded;
3224 }
3225 }
3226 if (what & DisplayState::eLayerStackChanged) {
3227 if (disp.layerStack != s.layerStack) {
3228 disp.layerStack = s.layerStack;
3229 flags |= eDisplayTransactionNeeded;
3230 }
3231 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003232 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003233 if (disp.orientation != s.orientation) {
3234 disp.orientation = s.orientation;
3235 flags |= eDisplayTransactionNeeded;
3236 }
3237 if (disp.frame != s.frame) {
3238 disp.frame = s.frame;
3239 flags |= eDisplayTransactionNeeded;
3240 }
3241 if (disp.viewport != s.viewport) {
3242 disp.viewport = s.viewport;
3243 flags |= eDisplayTransactionNeeded;
3244 }
3245 }
Michael Lentine47e45402014-07-18 15:34:25 -07003246 if (what & DisplayState::eDisplaySizeChanged) {
3247 if (disp.width != s.width) {
3248 disp.width = s.width;
3249 flags |= eDisplayTransactionNeeded;
3250 }
3251 if (disp.height != s.height) {
3252 disp.height = s.height;
3253 flags |= eDisplayTransactionNeeded;
3254 }
3255 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003256 }
3257 return flags;
3258}
3259
chaviwca27f252018-02-06 16:46:39 -08003260uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3261 const layer_state_t& s = composerState.state;
3262 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3263
Mathias Agopian13127d82013-03-05 17:47:11 -08003264 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003265 if (layer == nullptr) {
3266 return 0;
3267 }
3268
3269 if (layer->isPendingRemoval()) {
3270 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3271 return 0;
3272 }
3273
3274 uint32_t flags = 0;
3275
3276 const uint32_t what = s.what;
3277 bool geometryAppliesWithResize =
3278 what & layer_state_t::eGeometryAppliesWithResize;
3279 if (what & layer_state_t::ePositionChanged) {
3280 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3281 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003282 }
chaviw8b3871a2017-11-01 17:41:01 -07003283 }
3284 if (what & layer_state_t::eLayerChanged) {
3285 // NOTE: index needs to be calculated before we update the state
3286 const auto& p = layer->getParent();
3287 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003288 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003289 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003290 mCurrentState.layersSortedByZ.removeAt(idx);
3291 mCurrentState.layersSortedByZ.add(layer);
3292 // we need traversal (state changed)
3293 // AND transaction (list changed)
3294 flags |= eTransactionNeeded|eTraversalNeeded;
3295 }
chaviw8b3871a2017-11-01 17:41:01 -07003296 } else {
3297 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003298 flags |= eTransactionNeeded|eTraversalNeeded;
3299 }
3300 }
chaviw8b3871a2017-11-01 17:41:01 -07003301 }
3302 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003303 // NOTE: index needs to be calculated before we update the state
3304 const auto& p = layer->getParent();
3305 if (p == nullptr) {
3306 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3307 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3308 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 }
3314 } else {
3315 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3316 flags |= eTransactionNeeded|eTraversalNeeded;
3317 }
chaviw8b3871a2017-11-01 17:41:01 -07003318 }
3319 }
3320 if (what & layer_state_t::eSizeChanged) {
3321 if (layer->setSize(s.w, s.h)) {
3322 flags |= eTraversalNeeded;
3323 }
3324 }
3325 if (what & layer_state_t::eAlphaChanged) {
3326 if (layer->setAlpha(s.alpha))
3327 flags |= eTraversalNeeded;
3328 }
3329 if (what & layer_state_t::eColorChanged) {
3330 if (layer->setColor(s.color))
3331 flags |= eTraversalNeeded;
3332 }
3333 if (what & layer_state_t::eMatrixChanged) {
3334 if (layer->setMatrix(s.matrix))
3335 flags |= eTraversalNeeded;
3336 }
3337 if (what & layer_state_t::eTransparentRegionChanged) {
3338 if (layer->setTransparentRegionHint(s.transparentRegion))
3339 flags |= eTraversalNeeded;
3340 }
3341 if (what & layer_state_t::eFlagsChanged) {
3342 if (layer->setFlags(s.flags, s.mask))
3343 flags |= eTraversalNeeded;
3344 }
3345 if (what & layer_state_t::eCropChanged) {
3346 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3347 flags |= eTraversalNeeded;
3348 }
3349 if (what & layer_state_t::eFinalCropChanged) {
3350 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3351 flags |= eTraversalNeeded;
3352 }
3353 if (what & layer_state_t::eLayerStackChanged) {
3354 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3355 // We only allow setting layer stacks for top level layers,
3356 // everything else inherits layer stack from its parent.
3357 if (layer->hasParent()) {
3358 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3359 layer->getName().string());
3360 } else if (idx < 0) {
3361 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3362 "that also does not appear in the top level layer list. Something"
3363 " has gone wrong.", layer->getName().string());
3364 } else if (layer->setLayerStack(s.layerStack)) {
3365 mCurrentState.layersSortedByZ.removeAt(idx);
3366 mCurrentState.layersSortedByZ.add(layer);
3367 // we need traversal (state changed)
3368 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003369 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003370 }
3371 }
3372 if (what & layer_state_t::eDeferTransaction) {
3373 if (s.barrierHandle != nullptr) {
3374 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3375 } else if (s.barrierGbp != nullptr) {
3376 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3377 if (authenticateSurfaceTextureLocked(gbp)) {
3378 const auto& otherLayer =
3379 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3380 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3381 } else {
3382 ALOGE("Attempt to defer transaction to to an"
3383 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003384 }
3385 }
chaviw8b3871a2017-11-01 17:41:01 -07003386 // We don't trigger a traversal here because if no other state is
3387 // changed, we don't want this to cause any more work
3388 }
3389 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003390 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003391 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003392 if (!hadParent) {
3393 mCurrentState.layersSortedByZ.remove(layer);
3394 }
chaviw8b3871a2017-11-01 17:41:01 -07003395 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003396 }
chaviw8b3871a2017-11-01 17:41:01 -07003397 }
3398 if (what & layer_state_t::eReparentChildren) {
3399 if (layer->reparentChildren(s.reparentHandle)) {
3400 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003401 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003402 }
chaviw8b3871a2017-11-01 17:41:01 -07003403 if (what & layer_state_t::eDetachChildren) {
3404 layer->detachChildren();
3405 }
3406 if (what & layer_state_t::eOverrideScalingModeChanged) {
3407 layer->setOverrideScalingMode(s.overrideScalingMode);
3408 // We don't trigger a traversal here because if no other state is
3409 // changed, we don't want this to cause any more work
3410 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003411 return flags;
3412}
3413
chaviwca27f252018-02-06 16:46:39 -08003414void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3415 const layer_state_t& state = composerState.state;
3416 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3417
3418 sp<Layer> layer(client->getLayerUser(state.surface));
3419 if (layer == nullptr) {
3420 return;
3421 }
3422
3423 if (layer->isPendingRemoval()) {
3424 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3425 return;
3426 }
3427
3428 if (state.what & layer_state_t::eDestroySurface) {
3429 removeLayerLocked(mStateLock, layer);
3430 }
3431}
3432
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003433status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003434 const String8& name,
3435 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003436 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003437 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003438 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003439{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003440 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003441 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003442 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003443 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003444 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003445
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003446 status_t result = NO_ERROR;
3447
3448 sp<Layer> layer;
3449
Cody Northropbc755282017-03-31 12:00:08 -06003450 String8 uniqueName = getUniqueLayerName(name);
3451
Mathias Agopian3165cc22012-08-08 19:42:09 -07003452 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3453 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003454 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003455 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003456 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003457
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003458 break;
chaviw13fdc492017-06-27 12:40:18 -07003459 case ISurfaceComposerClient::eFXSurfaceColor:
3460 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003461 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003462 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003463 break;
3464 default:
3465 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003466 break;
3467 }
3468
Dan Stoza7d89d062015-04-30 13:29:25 -07003469 if (result != NO_ERROR) {
3470 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003471 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003472
Chia-I Wuab0c3192017-08-01 11:29:00 -07003473 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3474 // TODO b/64227542
3475 if (windowType == 441731) {
3476 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3477 layer->setPrimaryDisplayOnly();
3478 }
3479
Albert Chaulk479c60c2017-01-27 14:21:34 -05003480 layer->setInfo(windowType, ownerUid);
3481
Robert Carr1f0a16a2016-10-24 16:27:39 -07003482 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003483 if (result != NO_ERROR) {
3484 return result;
3485 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003486 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003487
3488 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003489 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003490}
3491
Cody Northropbc755282017-03-31 12:00:08 -06003492String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3493{
3494 bool matchFound = true;
3495 uint32_t dupeCounter = 0;
3496
3497 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3498 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3499
3500 // Loop over layers until we're sure there is no matching name
3501 while (matchFound) {
3502 matchFound = false;
3503 mDrawingState.traverseInZOrder([&](Layer* layer) {
3504 if (layer->getName() == uniqueName) {
3505 matchFound = true;
3506 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3507 }
3508 });
3509 }
3510
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003511 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3512 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003513
3514 return uniqueName;
3515}
3516
David Sodman0c69cad2017-08-21 12:12:51 -07003517status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003518 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3519 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003520{
3521 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003522 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003523 case PIXEL_FORMAT_TRANSPARENT:
3524 case PIXEL_FORMAT_TRANSLUCENT:
3525 format = PIXEL_FORMAT_RGBA_8888;
3526 break;
3527 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003528 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003529 break;
3530 }
3531
David Sodman0c69cad2017-08-21 12:12:51 -07003532 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3533 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003534 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003535 *handle = layer->getHandle();
3536 *gbp = layer->getProducer();
3537 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003538 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003539
David Sodman0c69cad2017-08-21 12:12:51 -07003540 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003541 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003542}
3543
chaviw13fdc492017-06-27 12:40:18 -07003544status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003545 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003546 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003547{
chaviw13fdc492017-06-27 12:40:18 -07003548 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003549 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003550 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003551}
3552
Mathias Agopianac9fa422013-02-11 16:40:36 -08003553status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003554{
Robert Carr9524cb32017-02-13 11:32:32 -08003555 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003556 status_t err = NO_ERROR;
3557 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003558 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003559 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003560 err = removeLayer(l);
3561 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3562 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003563 }
3564 return err;
3565}
3566
Mathias Agopian13127d82013-03-05 17:47:11 -08003567status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003568{
Mathias Agopian67106042013-03-14 19:18:13 -07003569 // called by ~LayerCleaner() when all references to the IBinder (handle)
3570 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003571 sp<Layer> l = layer.promote();
3572 if (l == nullptr) {
3573 // The layer has already been removed, carry on
3574 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003575 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003576 // If we have a parent, then we can continue to live as long as it does.
3577 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003578}
3579
Mathias Agopianb60314a2012-04-10 22:09:54 -07003580// ---------------------------------------------------------------------------
3581
Andy McFadden13a082e2012-08-24 10:16:42 -07003582void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003583 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003584 Vector<ComposerState> state;
3585 Vector<DisplayState> displays;
3586 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003587 d.what = DisplayState::eDisplayProjectionChanged |
3588 DisplayState::eLayerStackChanged;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003589 d.token = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003590 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003591 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003592 d.frame.makeInvalid();
3593 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003594 d.width = 0;
3595 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003596 displays.add(d);
3597 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003598 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3599 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003600
David Sodman105b7dc2017-11-04 20:28:14 -07003601 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003602 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003603 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003604
Brian Andersond0010582017-03-07 13:20:31 -08003605 // Use phase of 0 since phase is not known.
3606 // Use latency of 0, which will snap to the ideal latency.
3607 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003608}
3609
3610void SurfaceFlinger::initializeDisplays() {
3611 class MessageScreenInitialized : public MessageBase {
3612 SurfaceFlinger* flinger;
3613 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003614 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003615 virtual bool handler() {
3616 flinger->onInitializeDisplays();
3617 return true;
3618 }
3619 };
3620 sp<MessageBase> msg = new MessageScreenInitialized(this);
3621 postMessageAsync(msg); // we may be called from main thread, use async message
3622}
3623
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003624void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3625 bool stateLockHeld) {
3626 const int32_t displayId = display->getHwcDisplayId();
3627 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003628
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003629 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003630 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003631 return;
3632 }
3633
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003634 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003635 ALOGW("Trying to set power mode for virtual display");
3636 return;
3637 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003638
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003639 display->setPowerMode(mode);
3640
Lloyd Pique4dccc412018-01-22 17:21:36 -08003641 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003642 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003643 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003644 if (idx < 0) {
3645 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3646 return;
3647 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003648 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003649 }
3650
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003651 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003652 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003653 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003654 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003655 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003656 // FIXME: eventthread only knows about the main display right now
3657 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003658 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003659 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003660
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003661 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003662 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003663 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003664
3665 struct sched_param param = {0};
3666 param.sched_priority = 1;
3667 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3668 ALOGW("Couldn't set SCHED_FIFO on display on");
3669 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003670 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003671 // Turn off the display
3672 struct sched_param param = {0};
3673 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3674 ALOGW("Couldn't set SCHED_OTHER on display off");
3675 }
3676
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003677 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003678 disableHardwareVsync(true); // also cancels any in-progress resync
3679
Mathias Agopiancde87a32012-09-13 14:09:01 -07003680 // FIXME: eventthread only knows about the main display right now
3681 mEventThread->onScreenReleased();
3682 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003683
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003684 getHwComposer().setPowerMode(type, mode);
3685 mVisibleRegionsDirty = true;
3686 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003687 } else if (mode == HWC_POWER_MODE_DOZE ||
3688 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003689 // Update display while dozing
3690 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003691 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003692 // FIXME: eventthread only knows about the main display right now
3693 mEventThread->onScreenAcquired();
3694 resyncToHardwareVsync(true);
3695 }
3696 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3697 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003698 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003699 disableHardwareVsync(true); // also cancels any in-progress resync
3700 // FIXME: eventthread only knows about the main display right now
3701 mEventThread->onScreenReleased();
3702 }
3703 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003704 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003705 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003706 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003707 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003708
3709 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003710}
3711
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003712void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
3713 postMessageSync(new LambdaMessage([&]() {
3714 const auto display = getDisplayDevice(displayToken);
3715 if (!display) {
3716 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3717 displayToken.get());
3718 } else if (display->isVirtual()) {
3719 ALOGW("Attempt to set power mode %d for virtual display", mode);
3720 } else {
3721 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003722 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003723 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003724}
3725
3726// ---------------------------------------------------------------------------
3727
Lloyd Pique755e3192018-01-31 16:46:15 -08003728status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3729 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003730 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003731
Mathias Agopianbd115332013-04-18 16:41:04 -07003732 IPCThreadState* ipc = IPCThreadState::self();
3733 const int pid = ipc->getCallingPid();
3734 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003735
Mathias Agopianbd115332013-04-18 16:41:04 -07003736 if ((uid != AID_SHELL) &&
3737 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003738 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003739 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003740 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003741 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003742 // (this would indicate SF is stuck, but we want to be able to
3743 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003744 status_t err = mStateLock.timedLock(s2ns(1));
3745 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003746 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003747 result.appendFormat(
3748 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3749 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003750 }
3751
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003752 bool dumpAll = true;
3753 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003754 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003755
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003756 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003757 if ((index < numArgs) &&
3758 (args[index] == String16("--list"))) {
3759 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003760 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003761 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003762 }
3763
3764 if ((index < numArgs) &&
3765 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003766 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003767 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003768 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003769 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003770
3771 if ((index < numArgs) &&
3772 (args[index] == String16("--latency-clear"))) {
3773 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003774 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003775 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003776 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003777
3778 if ((index < numArgs) &&
3779 (args[index] == String16("--dispsync"))) {
3780 index++;
3781 mPrimaryDispSync.dump(result);
3782 dumpAll = false;
3783 }
Dan Stozab90cf072015-03-05 11:05:59 -08003784
3785 if ((index < numArgs) &&
3786 (args[index] == String16("--static-screen"))) {
3787 index++;
3788 dumpStaticScreenStats(result);
3789 dumpAll = false;
3790 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003791
3792 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003793 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003794 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003795 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003796 dumpAll = false;
3797 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003798
3799 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3800 index++;
3801 dumpWideColorInfo(result);
3802 dumpAll = false;
3803 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003804
3805 if ((index < numArgs) &&
3806 (args[index] == String16("--enable-layer-stats"))) {
3807 index++;
3808 mLayerStats.enable();
3809 dumpAll = false;
3810 }
3811
3812 if ((index < numArgs) &&
3813 (args[index] == String16("--disable-layer-stats"))) {
3814 index++;
3815 mLayerStats.disable();
3816 dumpAll = false;
3817 }
3818
3819 if ((index < numArgs) &&
3820 (args[index] == String16("--clear-layer-stats"))) {
3821 index++;
3822 mLayerStats.clear();
3823 dumpAll = false;
3824 }
3825
3826 if ((index < numArgs) &&
3827 (args[index] == String16("--dump-layer-stats"))) {
3828 index++;
3829 mLayerStats.dump(result);
3830 dumpAll = false;
3831 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003832
3833 if ((index < numArgs) &&
3834 (args[index] == String16("--display-identification"))) {
3835 index++;
3836 dumpDisplayIdentificationData(result);
3837 dumpAll = false;
3838 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003839
3840 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3841 index++;
3842 mTimeStats.parseArgs(asProto, args, index, result);
3843 dumpAll = false;
3844 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003845 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003846
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003847 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003848 if (asProto) {
3849 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3850 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3851 } else {
3852 dumpAllLocked(args, index, result);
3853 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003854 }
3855
Mathias Agopian9795c422009-08-26 16:36:26 -07003856 if (locked) {
3857 mStateLock.unlock();
3858 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003859 }
3860 write(fd, result.string(), result.size());
3861 return NO_ERROR;
3862}
3863
Dan Stozac7014012014-02-14 15:03:43 -08003864void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3865 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003866{
Robert Carr2047fae2016-11-28 14:09:09 -08003867 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003868 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003869 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003870}
3871
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003872void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003873 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003874{
3875 String8 name;
3876 if (index < args.size()) {
3877 name = String8(args[index]);
3878 index++;
3879 }
3880
David Sodman105b7dc2017-11-04 20:28:14 -07003881 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003882 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003883 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003884
3885 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003886 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003887 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003888 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003889 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003890 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003891 }
Robert Carr2047fae2016-11-28 14:09:09 -08003892 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003893 }
3894}
3895
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003896void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003897 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003898{
3899 String8 name;
3900 if (index < args.size()) {
3901 name = String8(args[index]);
3902 index++;
3903 }
3904
Robert Carr2047fae2016-11-28 14:09:09 -08003905 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003906 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003907 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003908 }
Robert Carr2047fae2016-11-28 14:09:09 -08003909 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003910
Svetoslavd85084b2014-03-20 10:28:31 -07003911 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003912}
3913
Jamie Gennis6547ff42013-07-16 20:12:42 -07003914// This should only be called from the main thread. Otherwise it would need
3915// the lock and should use mCurrentState rather than mDrawingState.
3916void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003917 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003918 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003919 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003920
3921 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3922}
3923
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003924void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003925{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003926 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003927
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003928 if (isLayerTripleBufferingDisabled())
3929 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003930
3931 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003932 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003933 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003934 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003935 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3936 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003937 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003938}
3939
Dan Stozab90cf072015-03-05 11:05:59 -08003940void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3941{
3942 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003943 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3944 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003945 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003946 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003947 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3948 b + 1, bucketTimeSec, percent);
3949 }
David Sodman4a36e932017-11-07 14:29:47 -08003950 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003951 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003952 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003953 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003954 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003955}
3956
Dan Stozae77c7662016-05-13 11:37:28 -07003957void SurfaceFlinger::recordBufferingStats(const char* layerName,
3958 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003959 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3960 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003961 for (const auto& segment : history) {
3962 if (!segment.usedThirdBuffer) {
3963 stats.twoBufferTime += segment.totalTime;
3964 }
3965 if (segment.occupancyAverage < 1.0f) {
3966 stats.doubleBufferedTime += segment.totalTime;
3967 } else if (segment.occupancyAverage < 2.0f) {
3968 stats.tripleBufferedTime += segment.totalTime;
3969 }
3970 ++stats.numSegments;
3971 stats.totalTime += segment.totalTime;
3972 }
3973}
3974
Brian Andersond6927fb2016-07-23 23:37:30 -07003975void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3976 result.appendFormat("Layer frame timestamps:\n");
3977
3978 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3979 const size_t count = currentLayers.size();
3980 for (size_t i=0 ; i<count ; i++) {
3981 currentLayers[i]->dumpFrameEvents(result);
3982 }
3983}
3984
Dan Stozae77c7662016-05-13 11:37:28 -07003985void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3986 result.append("Buffering stats:\n");
3987 result.append(" [Layer name] <Active time> <Two buffer> "
3988 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003989 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003990 typedef std::tuple<std::string, float, float, float> BufferTuple;
3991 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003992 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003993 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003994 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003995 if (stats.numSegments == 0) {
3996 continue;
3997 }
3998 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3999 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4000 stats.totalTime;
4001 float doubleBufferRatio = static_cast<float>(
4002 stats.doubleBufferedTime) / stats.totalTime;
4003 float tripleBufferRatio = static_cast<float>(
4004 stats.tripleBufferedTime) / stats.totalTime;
4005 sorted.insert({activeTime, {name, twoBufferRatio,
4006 doubleBufferRatio, tripleBufferRatio}});
4007 }
4008 for (const auto& sortedPair : sorted) {
4009 float activeTime = sortedPair.first;
4010 const BufferTuple& values = sortedPair.second;
4011 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4012 std::get<0>(values).c_str(), activeTime,
4013 std::get<1>(values), std::get<2>(values),
4014 std::get<3>(values));
4015 }
4016 result.append("\n");
4017}
4018
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004019void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004020 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004021 const int32_t hwcId = display->getHwcDisplayId();
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004022 const auto displayId = getHwComposer().getHwcDisplayId(hwcId);
4023 if (!displayId) {
4024 continue;
4025 }
4026
4027 result.appendFormat("Display %d: ", hwcId);
4028 uint8_t port;
4029 DisplayIdentificationData data;
4030 if (!getHwComposer().getDisplayIdentificationData(*displayId, &port, &data)) {
4031 result.append("no identification data\n");
4032 continue;
4033 }
4034
4035 if (!isEdid(data)) {
4036 result.append("unknown identification data: ");
4037 for (uint8_t byte : data) {
4038 result.appendFormat("%x ", byte);
4039 }
4040 result.append("\n");
4041 continue;
4042 }
4043
4044 const auto edid = parseEdid(data);
4045 if (!edid) {
4046 result.append("invalid EDID: ");
4047 for (uint8_t byte : data) {
4048 result.appendFormat("%x ", byte);
4049 }
4050 result.append("\n");
4051 continue;
4052 }
4053
4054 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4055 result.append(edid->displayName.data(), edid->displayName.length());
4056 result.append("\"\n");
4057 }
4058 result.append("\n");
4059}
4060
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004061void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4062 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004063 result.appendFormat("DisplayColorSetting: %s\n",
4064 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004065
4066 // TODO: print out if wide-color mode is active or not
4067
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004068 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004069 const int32_t hwcId = display->getHwcDisplayId();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004070 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4071 continue;
4072 }
4073
4074 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004075 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004076 for (auto&& mode : modes) {
4077 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4078 }
4079
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004080 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004081 result.appendFormat(" Current color mode: %s (%d)\n",
4082 decodeColorMode(currentMode).c_str(), currentMode);
4083 }
4084 result.append("\n");
4085}
4086
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004087LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004088 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004089 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4090 const State& state = useDrawing ? mDrawingState : mCurrentState;
4091 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004092 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004093 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004094 });
4095
4096 return layersProto;
4097}
4098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004099LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004100 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004101
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004102 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004103 resolution->set_w(display.getWidth());
4104 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004105
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004106 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4107 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4108 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004109
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004110 const int32_t hwcId = display.getHwcDisplayId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004111 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004112 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004113 LayerProto* layerProto = layersProto.add_layers();
4114 layer->writeToProto(layerProto, hwcId);
4115 }
4116 });
4117
4118 return layersProto;
4119}
4120
Mathias Agopian74d211a2013-04-22 16:55:35 +02004121void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4122 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004123{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004124 bool colorize = false;
4125 if (index < args.size()
4126 && (args[index] == String16("--color"))) {
4127 colorize = true;
4128 index++;
4129 }
4130
4131 Colorizer colorizer(colorize);
4132
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004133 // figure out if we're stuck somewhere
4134 const nsecs_t now = systemTime();
4135 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4136 const nsecs_t inTransaction(mDebugInTransaction);
4137 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4138 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4139
4140 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004141 * Dump library configuration.
4142 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004143
4144 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004145 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004146 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004147 appendSfConfigString(result);
4148 appendUiConfigString(result);
4149 appendGuiConfigString(result);
4150 result.append("\n");
4151
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004152 result.append("\nDisplay identification data:\n");
4153 dumpDisplayIdentificationData(result);
4154
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004155 result.append("\nWide-Color information:\n");
4156 dumpWideColorInfo(result);
4157
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004158 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004159 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004160 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004161 result.append(SyncFeatures::getInstance().toString());
4162 result.append("\n");
4163
David Sodman105b7dc2017-11-04 20:28:14 -07004164 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004165
Andy McFadden41d67d72014-04-25 16:58:34 -07004166 colorizer.bold(result);
4167 result.append("DispSync configuration: ");
4168 colorizer.reset(result);
Dan Stoza84d619e2018-03-28 17:07:36 -07004169 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4170 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4171 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004172 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004173 result.append("\n");
4174
Dan Stozab90cf072015-03-05 11:05:59 -08004175 // Dump static screen stats
4176 result.append("\n");
4177 dumpStaticScreenStats(result);
4178 result.append("\n");
4179
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004180 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4181
Dan Stozae77c7662016-05-13 11:37:28 -07004182 dumpBufferingStats(result);
4183
Andy McFadden4803b742012-09-24 19:07:20 -07004184 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004185 * Dump the visible layer list
4186 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004187 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004188 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004189 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4190 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004191 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004192
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004193 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004194 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004195 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004196 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004197
4198 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004199 * Dump Display state
4200 */
4201
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004202 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004203 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004204 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004205 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004206 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004207 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004208 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004209
4210 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004211 * Dump SurfaceFlinger global state
4212 */
4213
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004214 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004215 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004216 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004217
Mathias Agopian888c8222012-08-04 21:10:38 -07004218 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004219 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004220
David Sodmanbc815282017-11-05 18:57:52 -08004221 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004222
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004223 if (display) {
4224 display->undefinedRegion.dump(result, "undefinedRegion");
4225 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4226 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004227 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004228 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004229 " last eglSwapBuffers() time: %f us\n"
4230 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004231 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004232 " refresh-rate : %f fps\n"
4233 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004234 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004235 " gpu_to_cpu_unsupported : %d\n"
4236 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004237 mLastSwapBufferTime/1000.0,
4238 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004239 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004240 1e9 / activeConfig->getVsyncPeriod(),
4241 activeConfig->getDpiX(),
4242 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004243 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004244
Mathias Agopian74d211a2013-04-22 16:55:35 +02004245 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004246 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004247
Mathias Agopian74d211a2013-04-22 16:55:35 +02004248 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004249 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004250
4251 /*
4252 * VSYNC state
4253 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004254 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004255 result.append("\n");
4256
4257 /*
4258 * HWC layer minidump
4259 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004260 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004261 const int32_t hwcId = display->getHwcDisplayId();
Dan Stozae22aec72016-08-01 13:20:59 -07004262 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4263 continue;
4264 }
4265
4266 result.appendFormat("Display %d HWC layers:\n", hwcId);
4267 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004268 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004269 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004270 });
Dan Stozae22aec72016-08-01 13:20:59 -07004271 result.append("\n");
4272 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004273
4274 /*
4275 * Dump HWComposer state
4276 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004277 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004278 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004279 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004280 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004281 result.appendFormat(" h/w composer %s\n",
4282 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004283 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004284
4285 /*
4286 * Dump gralloc state
4287 */
4288 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4289 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004290
4291 /*
4292 * Dump VrFlinger state if in use.
4293 */
4294 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4295 result.append("VrFlinger state:\n");
4296 result.append(mVrFlinger->Dump().c_str());
4297 result.append("\n");
4298 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004299}
4300
Mathias Agopian13127d82013-03-05 17:47:11 -08004301const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004302SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004303 // Note: mStateLock is held here
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004304 wp<IBinder> displayToken;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004305 for (const auto& [token, display] : mDisplays) {
4306 if (display->getHwcDisplayId() == id) {
4307 displayToken = token;
Jesse Hall48bc05b2013-03-21 14:06:52 -07004308 break;
4309 }
4310 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004311 if (displayToken == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004312 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4313 // Just use the primary display so we have something to return
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004314 displayToken = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
Jesse Hall48bc05b2013-03-21 14:06:52 -07004315 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004316 return getDisplayDeviceLocked(displayToken)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004317}
4318
Keun young Park63f165f2012-08-31 10:53:36 -07004319bool SurfaceFlinger::startDdmConnection()
4320{
4321 void* libddmconnection_dso =
4322 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4323 if (!libddmconnection_dso) {
4324 return false;
4325 }
4326 void (*DdmConnection_start)(const char* name);
4327 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004328 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004329 if (!DdmConnection_start) {
4330 dlclose(libddmconnection_dso);
4331 return false;
4332 }
4333 (*DdmConnection_start)(getServiceName());
4334 return true;
4335}
4336
Chia-I Wu28f320b2018-05-03 11:02:56 -07004337void SurfaceFlinger::updateColorMatrixLocked() {
4338 mat4 colorMatrix;
4339 if (mGlobalSaturationFactor != 1.0f) {
4340 // Rec.709 luma coefficients
4341 float3 luminance{0.213f, 0.715f, 0.072f};
4342 luminance *= 1.0f - mGlobalSaturationFactor;
4343 mat4 saturationMatrix = mat4(
4344 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4345 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4346 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4347 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4348 );
4349 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4350 } else {
4351 colorMatrix = mClientColorMatrix * mDaltonizer();
4352 }
4353
4354 if (mCurrentState.colorMatrix != colorMatrix) {
4355 mCurrentState.colorMatrix = colorMatrix;
4356 mCurrentState.colorMatrixChanged = true;
4357 setTransactionFlags(eTransactionNeeded);
4358 }
4359}
4360
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004361status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004362 switch (code) {
4363 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004364 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004365 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004366 case CLEAR_ANIMATION_FRAME_STATS:
4367 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004368 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004369 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004370 case ENABLE_VSYNC_INJECTIONS:
4371 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004372 {
4373 // codes that require permission check
4374 IPCThreadState* ipc = IPCThreadState::self();
4375 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004376 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004377 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004378 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004379 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004380 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004381 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004382 break;
4383 }
Robert Carr1db73f62016-12-21 12:58:51 -08004384 /*
4385 * Calling setTransactionState is safe, because you need to have been
4386 * granted a reference to Client* and Handle* to do anything with it.
4387 *
4388 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4389 */
4390 case SET_TRANSACTION_STATE:
4391 case CREATE_SCOPED_CONNECTION:
4392 {
4393 return OK;
4394 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004395 case CAPTURE_SCREEN:
4396 {
4397 // codes that require permission check
4398 IPCThreadState* ipc = IPCThreadState::self();
4399 const int pid = ipc->getCallingPid();
4400 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004401 if ((uid != AID_GRAPHICS) &&
4402 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004403 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004404 return PERMISSION_DENIED;
4405 }
4406 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004407 }
chaviwa76b2712017-09-20 12:02:26 -07004408 case CAPTURE_LAYERS: {
4409 IPCThreadState* ipc = IPCThreadState::self();
4410 const int pid = ipc->getCallingPid();
4411 const int uid = ipc->getCallingUid();
4412 if ((uid != AID_GRAPHICS) &&
4413 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4414 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4415 return PERMISSION_DENIED;
4416 }
4417 break;
4418 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004419 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004420 return OK;
4421}
4422
4423status_t SurfaceFlinger::onTransact(
4424 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4425{
4426 status_t credentialCheck = CheckTransactCodeCredentials(code);
4427 if (credentialCheck != OK) {
4428 return credentialCheck;
4429 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004430
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004431 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4432 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004433 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004434 IPCThreadState* ipc = IPCThreadState::self();
4435 const int uid = ipc->getCallingUid();
4436 if (CC_UNLIKELY(uid != AID_SYSTEM
4437 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004438 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004439 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004440 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004441 return PERMISSION_DENIED;
4442 }
4443 int n;
4444 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004445 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004446 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004447 return NO_ERROR;
4448 case 1002: // SHOW_UPDATES
4449 n = data.readInt32();
4450 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004451 invalidateHwcGeometry();
4452 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004453 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004454 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004455 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004456 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004457 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004458 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004459 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004460 setTransactionFlags(
4461 eTransactionNeeded|
4462 eDisplayTransactionNeeded|
4463 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004464 return NO_ERROR;
4465 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004466 case 1006:{ // send empty update
4467 signalRefresh();
4468 return NO_ERROR;
4469 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004470 case 1008: // toggle use of hw composer
4471 n = data.readInt32();
4472 mDebugDisableHWC = n ? 1 : 0;
4473 invalidateHwcGeometry();
4474 repaintEverything();
4475 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004476 case 1009: // toggle use of transform hint
4477 n = data.readInt32();
4478 mDebugDisableTransformHint = n ? 1 : 0;
4479 invalidateHwcGeometry();
4480 repaintEverything();
4481 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004482 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004483 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004484 reply->writeInt32(0);
4485 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004486 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004487 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004488 return NO_ERROR;
4489 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004490 const auto display = getDefaultDisplayDevice();
4491 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004492 return NO_ERROR;
4493 }
4494 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004495 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004496 // daltonize
4497 n = data.readInt32();
4498 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004499 case 1:
4500 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4501 break;
4502 case 2:
4503 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4504 break;
4505 case 3:
4506 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4507 break;
4508 default:
4509 mDaltonizer.setType(ColorBlindnessType::None);
4510 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004511 }
4512 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004513 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004514 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004515 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004516 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004517
4518 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004519 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004520 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004521 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004522 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004523 // apply a color matrix
4524 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004525 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004526 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004527 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004528 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004529 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004530 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004531 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004532 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004533 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004534 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004535
4536 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4537 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004538 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004539 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4540 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4541 }
4542
Chia-I Wu28f320b2018-05-03 11:02:56 -07004543 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004544 return NO_ERROR;
4545 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004546 // This is an experimental interface
4547 // Needs to be shifted to proper binder interface when we productize
4548 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004549 n = data.readInt32();
4550 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004551 return NO_ERROR;
4552 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004553 case 1017: {
4554 n = data.readInt32();
4555 mForceFullDamage = static_cast<bool>(n);
4556 return NO_ERROR;
4557 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004558 case 1018: { // Modify Choreographer's phase offset
4559 n = data.readInt32();
4560 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4561 return NO_ERROR;
4562 }
4563 case 1019: { // Modify SurfaceFlinger's phase offset
4564 n = data.readInt32();
4565 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4566 return NO_ERROR;
4567 }
Irvel468051e2016-06-13 16:44:44 -07004568 case 1020: { // Layer updates interceptor
4569 n = data.readInt32();
4570 if (n) {
4571 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004572 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004573 }
4574 else{
4575 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004576 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004577 }
4578 return NO_ERROR;
4579 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004580 case 1021: { // Disable HWC virtual displays
4581 n = data.readInt32();
4582 mUseHwcVirtualDisplays = !n;
4583 return NO_ERROR;
4584 }
Romain Guy0147a172017-06-01 13:53:56 -07004585 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004586 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004587 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004588
Chia-I Wu28f320b2018-05-03 11:02:56 -07004589 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004590 return NO_ERROR;
4591 }
Romain Guy54f154a2017-10-24 21:40:32 +01004592 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004593 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004594 invalidateHwcGeometry();
4595 repaintEverything();
4596 return NO_ERROR;
4597 }
4598 case 1024: { // Is wide color gamut rendering/color management supported?
4599 reply->writeBool(hasWideColorDisplay);
4600 return NO_ERROR;
4601 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004602 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004603 n = data.readInt32();
4604 if (n) {
4605 ALOGV("LayerTracing enabled");
4606 mTracing.enable();
4607 doTracing("tracing.enable");
4608 reply->writeInt32(NO_ERROR);
4609 } else {
4610 ALOGV("LayerTracing disabled");
4611 status_t err = mTracing.disable();
4612 reply->writeInt32(err);
4613 }
4614 return NO_ERROR;
4615 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004616 case 1026: { // Get layer tracing status
4617 reply->writeBool(mTracing.isEnabled());
4618 return NO_ERROR;
4619 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004620 // Is a DisplayColorSetting supported?
4621 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004622 const auto display = getDefaultDisplayDevice();
4623 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004624 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004625 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004626
4627 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4628 switch (setting) {
4629 case DisplayColorSetting::MANAGED:
4630 reply->writeBool(hasWideColorDisplay);
4631 break;
4632 case DisplayColorSetting::UNMANAGED:
4633 reply->writeBool(true);
4634 break;
4635 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004636 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004637 break;
4638 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004639 reply->writeBool(
4640 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004641 break;
4642 }
4643 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004644 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004645 }
4646 }
4647 return err;
4648}
4649
Steven Thomas6d8110b2017-08-31 18:24:21 -07004650void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004651 android_atomic_or(1, &mRepaintEverything);
4652 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004653}
4654
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004655// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4656class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004657public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004658 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4659 ~WindowDisconnector() {
4660 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004661 }
4662
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004663private:
4664 ANativeWindow* mWindow;
4665 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004666};
4667
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004668status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4669 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4670 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4671 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004672 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004673 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004674
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004675 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004676
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004677 const auto display = getDisplayDeviceLocked(displayToken);
4678 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004679
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004680 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004681
4682 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004683 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004684 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004685}
4686
4687status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004688 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004689 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004690 ATRACE_CALL();
4691
4692 class LayerRenderArea : public RenderArea {
4693 public:
Robert Carr578038f2018-03-09 12:25:24 -08004694 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4695 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004696 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004697 mLayer(layer),
4698 mCrop(crop),
4699 mFlinger(flinger),
4700 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004701 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004702 Rect getBounds() const override {
4703 const Layer::State& layerState(mLayer->getDrawingState());
4704 return Rect(layerState.active.w, layerState.active.h);
4705 }
4706 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4707 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4708 bool isSecure() const override { return false; }
4709 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004710 Rect getSourceCrop() const override {
4711 if (mCrop.isEmpty()) {
4712 return getBounds();
4713 } else {
4714 return mCrop;
4715 }
4716 }
Robert Carr578038f2018-03-09 12:25:24 -08004717 class ReparentForDrawing {
4718 public:
4719 const sp<Layer>& oldParent;
4720 const sp<Layer>& newParent;
4721
4722 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4723 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004724 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004725 }
Robert Carr15eae092018-03-23 13:43:53 -07004726 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004727 };
4728
4729 void render(std::function<void()> drawLayers) override {
4730 if (!mChildrenOnly) {
4731 mTransform = mLayer->getTransform().inverse();
4732 drawLayers();
4733 } else {
4734 Rect bounds = getBounds();
4735 screenshotParentLayer =
4736 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4737 bounds.getWidth(), bounds.getHeight(), 0);
4738
4739 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4740 drawLayers();
4741 }
4742 }
chaviwa76b2712017-09-20 12:02:26 -07004743
chaviwa76b2712017-09-20 12:02:26 -07004744 private:
chaviw7206d492017-11-10 16:16:12 -08004745 const sp<Layer> mLayer;
4746 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004747
4748 // In the "childrenOnly" case we reparent the children to a screenshot
4749 // layer which has no properties set and which does not draw.
4750 sp<ContainerLayer> screenshotParentLayer;
4751 Transform mTransform;
4752
4753 SurfaceFlinger* mFlinger;
4754 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004755 };
4756
4757 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4758 auto parent = layerHandle->owner.promote();
4759
chaviw7206d492017-11-10 16:16:12 -08004760 if (parent == nullptr || parent->isPendingRemoval()) {
4761 ALOGE("captureLayers called with a removed parent");
4762 return NAME_NOT_FOUND;
4763 }
4764
Robert Carr578038f2018-03-09 12:25:24 -08004765 const int uid = IPCThreadState::self()->getCallingUid();
4766 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4767 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4768 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4769 return PERMISSION_DENIED;
4770 }
4771
chaviw7206d492017-11-10 16:16:12 -08004772 Rect crop(sourceCrop);
4773 if (sourceCrop.width() <= 0) {
4774 crop.left = 0;
4775 crop.right = parent->getCurrentState().active.w;
4776 }
4777
4778 if (sourceCrop.height() <= 0) {
4779 crop.top = 0;
4780 crop.bottom = parent->getCurrentState().active.h;
4781 }
4782
4783 int32_t reqWidth = crop.width() * frameScale;
4784 int32_t reqHeight = crop.height() * frameScale;
4785
Robert Carr578038f2018-03-09 12:25:24 -08004786 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004787
Robert Carr578038f2018-03-09 12:25:24 -08004788 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004789 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4790 if (!layer->isVisible()) {
4791 return;
Robert Carr578038f2018-03-09 12:25:24 -08004792 } else if (childrenOnly && layer == parent.get()) {
4793 return;
chaviwa76b2712017-09-20 12:02:26 -07004794 }
4795 visitor(layer);
4796 });
4797 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004798 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004799}
4800
4801status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4802 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004803 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004804 bool useIdentityTransform) {
4805 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004806
Iris Chang7501ed62018-04-30 14:45:42 +08004807 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004808
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004809 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4810 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4811 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4812 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004813
4814 // This mutex protects syncFd and captureResult for communication of the return values from the
4815 // main thread back to this Binder thread
4816 std::mutex captureMutex;
4817 std::condition_variable captureCondition;
4818 std::unique_lock<std::mutex> captureLock(captureMutex);
4819 int syncFd = -1;
4820 std::optional<status_t> captureResult;
4821
Robert Carr03480e22018-01-04 16:02:06 -08004822 const int uid = IPCThreadState::self()->getCallingUid();
4823 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4824
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004825 sp<LambdaMessage> message = new LambdaMessage([&]() {
4826 // If there is a refresh pending, bug out early and tell the binder thread to try again
4827 // after the refresh.
4828 if (mRefreshPending) {
4829 ATRACE_NAME("Skipping screenshot for now");
4830 std::unique_lock<std::mutex> captureLock(captureMutex);
4831 captureResult = std::make_optional<status_t>(EAGAIN);
4832 captureCondition.notify_one();
4833 return;
4834 }
4835
4836 status_t result = NO_ERROR;
4837 int fd = -1;
4838 {
4839 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004840 renderArea.render([&]() {
4841 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4842 useIdentityTransform, forSystem, &fd);
4843 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004844 }
4845
4846 {
4847 std::unique_lock<std::mutex> captureLock(captureMutex);
4848 syncFd = fd;
4849 captureResult = std::make_optional<status_t>(result);
4850 captureCondition.notify_one();
4851 }
4852 });
4853
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004854 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004855 if (result == NO_ERROR) {
4856 captureCondition.wait(captureLock, [&]() { return captureResult; });
4857 while (*captureResult == EAGAIN) {
4858 captureResult.reset();
4859 result = postMessageAsync(message);
4860 if (result != NO_ERROR) {
4861 return result;
4862 }
4863 captureCondition.wait(captureLock, [&]() { return captureResult; });
4864 }
4865 result = *captureResult;
4866 }
4867
4868 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004869 sync_wait(syncFd, -1);
4870 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004871 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004872
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004873 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004874}
4875
chaviwa76b2712017-09-20 12:02:26 -07004876void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4877 TraverseLayersFunction traverseLayers, bool yswap,
4878 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004879 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004880
Lloyd Pique144e1162017-12-20 16:44:52 -08004881 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004882
4883 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004884 const auto raWidth = renderArea.getWidth();
4885 const auto raHeight = renderArea.getHeight();
4886
4887 const auto reqWidth = renderArea.getReqWidth();
4888 const auto reqHeight = renderArea.getReqHeight();
4889 Rect sourceCrop = renderArea.getSourceCrop();
4890
Iris Chang7501ed62018-04-30 14:45:42 +08004891 bool filtering = false;
4892 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4893 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
4894 static_cast<int32_t>(reqHeight) != raWidth;
4895 } else {
4896 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4897 static_cast<int32_t>(reqHeight) != raHeight;
4898 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004899
Dan Stozac1879002014-05-22 15:59:05 -07004900 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004901 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004902 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004903 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08004904 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4905 Transform tr;
4906 uint32_t flags = 0x00;
4907 switch (mPrimaryDisplayOrientation) {
4908 case DisplayState::eOrientation90:
4909 flags = Transform::ROT_90;
4910 break;
4911 case DisplayState::eOrientation180:
4912 flags = Transform::ROT_180;
4913 break;
4914 case DisplayState::eOrientation270:
4915 flags = Transform::ROT_270;
4916 break;
4917 }
4918 tr.set(flags, raWidth, raHeight);
4919 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07004920 }
4921
4922 // ensure that sourceCrop is inside screen
4923 if (sourceCrop.left < 0) {
4924 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4925 }
chaviwa76b2712017-09-20 12:02:26 -07004926 if (sourceCrop.right > raWidth) {
4927 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004928 }
4929 if (sourceCrop.top < 0) {
4930 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4931 }
chaviwa76b2712017-09-20 12:02:26 -07004932 if (sourceCrop.bottom > raHeight) {
4933 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004934 }
4935
Chia-I Wu36574d92018-05-16 10:54:36 -07004936 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
4937 engine.setOutputDataSpace(Dataspace::SRGB);
4938 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07004939
Mathias Agopian180f10d2013-04-10 22:55:41 -07004940 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004941 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004942
Iris Chang7501ed62018-04-30 14:45:42 +08004943 Transform::orientation_flags rotation = renderArea.getRotationFlags();
4944 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4945 // convert hw orientation into flag presentation
4946 // here inverse transform needed
4947 uint8_t hw_rot_90 = 0x00;
4948 uint8_t hw_flip_hv = 0x00;
4949 switch (mPrimaryDisplayOrientation) {
4950 case DisplayState::eOrientation90:
4951 hw_rot_90 = Transform::ROT_90;
4952 hw_flip_hv = Transform::ROT_180;
4953 break;
4954 case DisplayState::eOrientation180:
4955 hw_flip_hv = Transform::ROT_180;
4956 break;
4957 case DisplayState::eOrientation270:
4958 hw_rot_90 = Transform::ROT_90;
4959 break;
4960 }
4961
4962 // transform flags operation
4963 // 1) flip H V if both have ROT_90 flag
4964 // 2) XOR these flags
4965 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
4966 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
4967 if (rotation_rot_90 & hw_rot_90) {
4968 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
4969 }
4970 rotation = static_cast<Transform::orientation_flags>
4971 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
4972 }
4973
Mathias Agopian180f10d2013-04-10 22:55:41 -07004974 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004975 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08004976 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004977 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004978
chaviw50da5042018-04-09 13:49:37 -07004979 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004980 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004981 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004982
chaviwa76b2712017-09-20 12:02:26 -07004983 traverseLayers([&](Layer* layer) {
4984 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07004985 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004986 if (filtering) layer->setFiltering(false);
4987 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004988}
4989
chaviwa76b2712017-09-20 12:02:26 -07004990status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4991 TraverseLayersFunction traverseLayers,
4992 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004993 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004994 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004995 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004996 ATRACE_CALL();
4997
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004998 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004999
5000 traverseLayers([&](Layer* layer) {
5001 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5002 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005003
Robert Carr03480e22018-01-04 16:02:06 -08005004 // We allow the system server to take screenshots of secure layers for
5005 // use in situations like the Screen-rotation animation and place
5006 // the impetus on WindowManager to not persist them.
5007 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005008 ALOGW("FB is protected: PERMISSION_DENIED");
5009 return PERMISSION_DENIED;
5010 }
5011
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005012 // this binds the given EGLImage as a framebuffer for the
5013 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005014 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005015 if (bufferBond.getStatus() != NO_ERROR) {
5016 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005017 return INVALID_OPERATION;
5018 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005019
Dan Stozaabcda352017-06-01 14:37:39 -07005020 // this will in fact render into our dequeued buffer
5021 // via an FBO, which means we didn't have to create
5022 // an EGLSurface and therefore we're not
5023 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005024 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005025
Dan Stozaabcda352017-06-01 14:37:39 -07005026 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005027 getRenderEngine().finish();
5028 *outSyncFd = -1;
5029
chaviwa76b2712017-09-20 12:02:26 -07005030 const auto reqWidth = renderArea.getReqWidth();
5031 const auto reqHeight = renderArea.getReqHeight();
5032
Dan Stozaabcda352017-06-01 14:37:39 -07005033 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5034 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005035 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005036 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005037 } else {
5038 base::unique_fd syncFd = getRenderEngine().flush();
5039 if (syncFd < 0) {
5040 getRenderEngine().finish();
5041 }
5042 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005043 }
5044
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005045 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005046}
5047
Mathias Agopiand5556842013-09-19 17:08:37 -07005048void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005049 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005050 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005051 for (size_t y = 0; y < h; y++) {
5052 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5053 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005054 if (p[x] != 0xFF000000) return;
5055 }
5056 }
chaviwa76b2712017-09-20 12:02:26 -07005057 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005058
Robert Carr2047fae2016-11-28 14:09:09 -08005059 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005060 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005061 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005062 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5063 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5064 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5065 static_cast<float>(state.color.a));
5066 i++;
5067 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005068 }
5069}
5070
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005071// ---------------------------------------------------------------------------
5072
Dan Stoza412903f2017-04-27 13:42:17 -07005073void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5074 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005075}
5076
Dan Stoza412903f2017-04-27 13:42:17 -07005077void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5078 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005079}
5080
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005081void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5082 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005083 const LayerVector::Visitor& visitor) {
5084 // We loop through the first level of layers without traversing,
5085 // as we need to interpret min/max layer Z in the top level Z space.
5086 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005087 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005088 continue;
5089 }
5090 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005091 // relative layers are traversed in Layer::traverseInZOrder
5092 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005093 continue;
5094 }
5095 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005096 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005097 return;
5098 }
chaviwa76b2712017-09-20 12:02:26 -07005099 if (!layer->isVisible()) {
5100 return;
5101 }
5102 visitor(layer);
5103 });
5104 }
5105}
5106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005107}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005108
Chia-I Wu30505fb2018-03-26 16:20:31 -07005109
Mathias Agopian3f844832013-08-07 21:24:32 -07005110#if defined(__gl_h_)
5111#error "don't include gl/gl.h in this file"
5112#endif
5113
5114#if defined(__gl2_h_)
5115#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005116#endif