blob: 16c143f513188b49a957d856e23f1dda206083fd [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 Laskowski7e045462018-05-30 13:02:02 -07001505 getBE().mHwc->hasClientComposition(display->getId());
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)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001550 display->getId(), 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 Laskowski7e045462018-05-30 13:02:02 -07001792 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
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 Laskowski7e045462018-05-30 13:02:02 -07001798 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
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)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001920 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
1921 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 Laskowski7e045462018-05-30 13:02:02 -07001934 const auto displayId = display->getId();
1935 if (displayId >= 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];
Dominik Laskowski7e045462018-05-30 13:02:02 -07001939 if (!layer->hasHwcLayer(displayId)) {
1940 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1941 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001942 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) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001948 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001949 }
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 Laskowski7e045462018-05-30 13:02:02 -07001957 const auto displayId = display->getId();
1958 if (displayId < 0) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001959 continue;
1960 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07001961
Chia-I Wu28f320b2018-05-03 11:02:56 -07001962 if (mDrawingState.colorMatrixChanged) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001963 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski7e045462018-05-30 13:02:02 -07001964 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001965 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001966 displayId, 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()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001972 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001973 }
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()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001977 layer->forceClientComposition(displayId);
Peiyong Linf59a7192018-04-25 11:19:31 -07001978 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001979
Dominik Laskowski7e045462018-05-30 13:02:02 -07001980 if (layer->getForceClientComposition(displayId)) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001981 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07001982 layer->setCompositionType(displayId, HWC2::Composition::Client);
Chia-I Wu30505fb2018-03-26 16:20:31 -07001983 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)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002007 display->getId(), 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 Laskowski7e045462018-05-30 13:02:02 -07002043 const auto displayId = display->getId();
2044 if (displayId >= 0) {
2045 getBE().mHwc->presentAndGetReleaseFences(displayId);
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.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002053 auto hwcLayer = layer->getHwcLayer(displayId);
2054 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, 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.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002061 if (layer->getCompositionType(displayId) == 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()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002073 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
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
Dominik Laskowski7e045462018-05-30 13:02:02 -07002079 if (displayId >= 0) {
2080 getBE().mHwc->clearReleaseFences(displayId);
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
Dominik Laskowski7e045462018-05-30 13:02:02 -07002126DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
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.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002135 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2136 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002137 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002138 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002139 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002140 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002141 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002142 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002143 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002144 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002145 return DisplayDevice::DISPLAY_EXTERNAL;
2146 }
2147
2148 return DisplayDevice::DISPLAY_ID_INVALID;
2149}
2150
Lloyd Piqueba04e622017-12-14 17:11:26 -08002151void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2152 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002153 auto displayType = determineDisplayType(event.display, event.connection);
2154 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2155 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2156 continue;
2157 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002158
2159 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2160 ALOGE("External displays are not supported by the vr hardware composer.");
2161 continue;
2162 }
2163
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002164 const auto displayId =
2165 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
2166 if (displayId) {
2167 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.display, *displayId);
2168 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002169
2170 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002171 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002172 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002173 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002174 DisplayDeviceState info;
2175 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002176 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2177 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002178 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002179 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002180 mInterceptor->saveDisplayCreation(info);
2181 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002182 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002183 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002184
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002185 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002186 if (idx >= 0) {
2187 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002188 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002189 mCurrentState.displays.removeItemsAt(idx);
2190 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002191 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002192 }
2193
2194 processDisplayChangesLocked();
2195 }
2196
2197 mPendingHotplugEvents.clear();
2198}
2199
Lloyd Pique99d3da52018-01-22 17:48:03 -08002200sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002201 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002202 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002203 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002204 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002205
Lloyd Pique99d3da52018-01-22 17:48:03 -08002206 if (hasWideColorDisplay) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002207 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002208 for (ColorMode colorMode : modes) {
2209 switch (colorMode) {
2210 case ColorMode::DISPLAY_P3:
2211 case ColorMode::ADOBE_RGB:
2212 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002213 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002214 break;
2215 default:
2216 break;
2217 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002218
Dominik Laskowski7e045462018-05-30 13:02:02 -07002219 std::vector<RenderIntent> renderIntents =
2220 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002221 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002222 }
2223 }
2224
Peiyong Lin62665892018-04-16 11:07:44 -07002225 HdrCapabilities hdrCapabilities;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002226 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002227
2228 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2229 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2230
2231 /*
2232 * Create our display's surface
2233 */
2234 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2235 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002236 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002237 renderSurface->setNativeWindow(nativeWindow.get());
2238 const int displayWidth = renderSurface->queryWidth();
2239 const int displayHeight = renderSurface->queryHeight();
2240
2241 // Make sure that composition can never be stalled by a virtual display
2242 // consumer that isn't processing buffers fast enough. We have to do this
2243 // in two places:
2244 // * Here, in case the display is composed entirely by HWC.
2245 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2246 // window's swap interval in eglMakeCurrent, so they'll override the
2247 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002248 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002249 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2250 }
2251
2252 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002253 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002254
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002255 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002256 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2257 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2258 displayHeight, hasWideColorGamut, hdrCapabilities,
2259 getHwComposer().getSupportedPerFrameMetadata(displayId),
2260 hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002261
2262 if (maxFrameBufferAcquiredBuffers >= 3) {
2263 nativeWindowSurface->preallocateBuffers();
2264 }
2265
2266 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002267 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2268 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002269 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002270 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002271 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002272 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002273 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002274 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002275 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002276 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002277 display->setLayerStack(state.layerStack);
2278 display->setProjection(state.orientation, state.viewport, state.frame);
2279 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002280
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002281 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002282}
2283
Lloyd Pique347200f2017-12-14 17:00:15 -08002284void SurfaceFlinger::processDisplayChangesLocked() {
2285 // here we take advantage of Vector's copy-on-write semantics to
2286 // improve performance by skipping the transaction entirely when
2287 // know that the lists are identical
2288 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2289 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2290 if (!curr.isIdenticalTo(draw)) {
2291 mVisibleRegionsDirty = true;
2292 const size_t cc = curr.size();
2293 size_t dc = draw.size();
2294
2295 // find the displays that were removed
2296 // (ie: in drawing state but not in current state)
2297 // also handle displays that changed
2298 // (ie: displays that are in both lists)
2299 for (size_t i = 0; i < dc;) {
2300 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2301 if (j < 0) {
2302 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002303 // Call makeCurrent() on the primary display so we can
2304 // be sure that nothing associated with this display
2305 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002306 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2307 defaultDisplay->makeCurrent();
2308 }
2309 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2310 display->disconnect(getHwComposer());
2311 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002312 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2313 mEventThread->onHotplugReceived(draw[i].type, false);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002314 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002315 } else {
2316 // this display is in both lists. see if something changed.
2317 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002318 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002319 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2320 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2321 if (state_binder != draw_binder) {
2322 // changing the surface is like destroying and
2323 // recreating the DisplayDevice, so we just remove it
2324 // from the drawing state, so that it get re-added
2325 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002326 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2327 display->disconnect(getHwComposer());
2328 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002329 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002330 mDrawingState.displays.removeItemsAt(i);
2331 dc--;
2332 // at this point we must loop to the next item
2333 continue;
2334 }
2335
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002336 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002337 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002338 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002339 }
2340 if ((state.orientation != draw[i].orientation) ||
2341 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002342 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002343 }
2344 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002345 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002346 }
2347 }
2348 }
2349 ++i;
2350 }
2351
2352 // find displays that were added
2353 // (ie: in current state but not in drawing state)
2354 for (size_t i = 0; i < cc; i++) {
2355 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2356 const DisplayDeviceState& state(curr[i]);
2357
2358 sp<DisplaySurface> dispSurface;
2359 sp<IGraphicBufferProducer> producer;
2360 sp<IGraphicBufferProducer> bqProducer;
2361 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002362 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002363
Dominik Laskowski7e045462018-05-30 13:02:02 -07002364 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002365 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002366 // Virtual displays without a surface are dormant:
2367 // they have external state (layer stack, projection,
2368 // etc.) but no internal state (i.e. a DisplayDevice).
2369 if (state.surface != nullptr) {
2370 // Allow VR composer to use virtual displays.
2371 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2372 int width = 0;
2373 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2374 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2375 int height = 0;
2376 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2377 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2378 int intFormat = 0;
2379 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2380 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002381 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002382
Dominik Laskowski7e045462018-05-30 13:02:02 -07002383 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2384 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002385 }
2386
2387 // TODO: Plumb requested format back up to consumer
2388
2389 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002390 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002391 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
Dominik Laskowski7e045462018-05-30 13:02:02 -07002403 displayId = state.type;
2404 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002405 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,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002411 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002412 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 Laskowski7e045462018-05-30 13:02:02 -07002559 if (display->getId() < 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 Laskowski7e045462018-05-30 13:02:02 -07002807 bool isHwcDisplay = display->getId() >= 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);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002825 const auto displayId = display->getId();
2826 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
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
Dominik Laskowski7e045462018-05-30 13:02:02 -07002844 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002845 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());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002923 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002924 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002925 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002926 case HWC2::Composition::Cursor:
2927 case HWC2::Composition::Device:
2928 case HWC2::Composition::Sideband:
2929 case HWC2::Composition::SolidColor: {
2930 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002931 if (layer->getClearClientTarget(displayId) && !firstLayer &&
2932 layer->isOpaque(state) && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002933 // never clear the very first layer since we're
2934 // guaranteed the FB is already cleared
2935 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002936 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002937 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002938 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002939 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002940 // switch color matrices lazily
Peiyong Lin00f9c022018-05-09 15:35:33 -07002941 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
2942 if (!legacyColorMatrixApplied) {
2943 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
2944 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002945 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07002946 } else if (legacyColorMatrixApplied) {
2947 getRenderEngine().setSaturationMatrix(mat4());
2948 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002949 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07002950
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002951 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002952 break;
2953 }
2954 default:
2955 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002956 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002957 } else {
2958 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002959 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002960 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002961 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002962
Peiyong Lin00f9c022018-05-09 15:35:33 -07002963 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002964 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002965 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07002966 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
2967 getRenderEngine().setSaturationMatrix(mat4());
2968 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002969
Mathias Agopianf45c5102012-10-24 16:29:17 -07002970 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002971 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002972 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002973}
2974
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002975void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2976 const Region& region) const {
2977 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002978 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002979 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002980}
2981
Dan Stoza7d89d062015-04-30 13:29:25 -07002982status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002983 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002984 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002985 const sp<Layer>& lbc,
2986 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002987{
Dan Stoza7d89d062015-04-30 13:29:25 -07002988 // add this layer to the current state list
2989 {
2990 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002991 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002992 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2993 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002994 return NO_MEMORY;
2995 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002996 if (parent == nullptr) {
2997 mCurrentState.layersSortedByZ.add(lbc);
2998 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002999 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003000 ALOGE("addClientLayer called with a removed parent");
3001 return NAME_NOT_FOUND;
3002 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003003 parent->addChild(lbc);
3004 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003005
Yiwei Zhang243b3782018-05-15 17:40:04 -07003006 if (gbc != nullptr) {
3007 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3008 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3009 mMaxGraphicBufferProducerListSize,
3010 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3011 mGraphicBufferProducerList.size(),
3012 mMaxGraphicBufferProducerListSize, mNumLayers);
3013 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003014 mLayersAdded = true;
3015 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003016 }
3017
Mathias Agopian96f08192010-06-02 23:28:45 -07003018 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003019 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003020
Dan Stoza7d89d062015-04-30 13:29:25 -07003021 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003022}
3023
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003024status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003025 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003026 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3027}
Robert Carr7f9b8992017-03-10 11:08:39 -08003028
chaviwca27f252018-02-06 16:46:39 -08003029status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3030 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003031 if (layer->isPendingRemoval()) {
3032 return NO_ERROR;
3033 }
3034
Robert Carr1f0a16a2016-10-24 16:27:39 -07003035 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003036 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003037 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003038 if (topLevelOnly) {
3039 return NO_ERROR;
3040 }
3041
Chia-I Wu98f1c102017-05-30 14:54:08 -07003042 sp<Layer> ancestor = p;
3043 while (ancestor->getParent() != nullptr) {
3044 ancestor = ancestor->getParent();
3045 }
3046 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3047 ALOGE("removeLayer called with a layer whose parent has been removed");
3048 return NAME_NOT_FOUND;
3049 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003050
3051 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003052 } else {
3053 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003054 }
3055
Robert Carr136e2f62017-02-08 17:54:29 -08003056 // As a matter of normal operation, the LayerCleaner will produce a second
3057 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3058 // so we will succeed in promoting it, but it's already been removed
3059 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3060 // otherwise something has gone wrong and we are leaking the layer.
3061 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003062 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3063 layer->getName().string(),
3064 (p != nullptr) ? p->getName().string() : "no-parent");
3065 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003066 } else if (index < 0) {
3067 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003068 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003069
Chia-I Wuc6657022017-08-15 11:18:17 -07003070 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003071 mLayersPendingRemoval.add(layer);
3072 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003073 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003074 setTransactionFlags(eTransactionNeeded);
3075 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076}
3077
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003078uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003079 return android_atomic_release_load(&mTransactionFlags);
3080}
3081
Mathias Agopian3f844832013-08-07 21:24:32 -07003082uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3084}
3085
Mathias Agopian3f844832013-08-07 21:24:32 -07003086uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003087 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3088}
3089
3090uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3091 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003093 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003094 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003095 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096 }
3097 return old;
3098}
3099
chaviwca27f252018-02-06 16:46:39 -08003100bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3101 for (const ComposerState& state : states) {
3102 // Here we need to check that the interface we're given is indeed
3103 // one of our own. A malicious client could give us a nullptr
3104 // IInterface, or one of its own or even one of our own but a
3105 // different type. All these situations would cause us to crash.
3106 if (state.client == nullptr) {
3107 return true;
3108 }
3109
3110 sp<IBinder> binder = IInterface::asBinder(state.client);
3111 if (binder == nullptr) {
3112 return true;
3113 }
3114
3115 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3116 return true;
3117 }
3118 }
3119 return false;
3120}
3121
Mathias Agopian8b33f032012-07-24 20:43:54 -07003122void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003123 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003124 const Vector<DisplayState>& displays,
3125 uint32_t flags)
3126{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003127 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003128 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003129 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003130
chaviwca27f252018-02-06 16:46:39 -08003131 if (containsAnyInvalidClientState(states)) {
3132 return;
3133 }
3134
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003135 if (flags & eAnimation) {
3136 // For window updates that are part of an animation we must wait for
3137 // previous animation "frames" to be handled.
3138 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003139 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003140 if (CC_UNLIKELY(err != NO_ERROR)) {
3141 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003142 // caller after a few seconds.
3143 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3144 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003145 mAnimTransactionPending = false;
3146 break;
3147 }
3148 }
3149 }
3150
chaviwca27f252018-02-06 16:46:39 -08003151 for (const DisplayState& display : displays) {
3152 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003153 }
3154
chaviwca27f252018-02-06 16:46:39 -08003155 for (const ComposerState& state : states) {
3156 transactionFlags |= setClientStateLocked(state);
3157 }
3158
3159 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3160 // as destroyed should only occur after setting all other states. This is to allow for a
3161 // child re-parent to happen before marking its original parent as destroyed (which would
3162 // then mark the child as destroyed).
3163 for (const ComposerState& state : states) {
3164 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003165 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003166
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003167 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3168 // anyway. This can be used as a flush mechanism for previous async transactions.
3169 // Empty animation transaction can be used to simulate back-pressure, so also force a
3170 // transaction for empty animation transactions.
3171 if (transactionFlags == 0 &&
3172 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003173 transactionFlags = eTransactionNeeded;
3174 }
3175
Mathias Agopian386aa982011-11-07 21:58:03 -08003176 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003177 if (mInterceptor->isEnabled()) {
3178 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003179 }
Irvel468051e2016-06-13 16:44:44 -07003180
Mathias Agopian386aa982011-11-07 21:58:03 -08003181 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003182 const auto start = (flags & eEarlyWakeup)
3183 ? VSyncModulator::TransactionStart::EARLY
3184 : VSyncModulator::TransactionStart::NORMAL;
3185 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003186
3187 // if this is a synchronous transaction, wait for it to take effect
3188 // before returning.
3189 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003190 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003191 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003192 if (flags & eAnimation) {
3193 mAnimTransactionPending = true;
3194 }
3195 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003196 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3197 if (CC_UNLIKELY(err != NO_ERROR)) {
3198 // just in case something goes wrong in SF, return to the
3199 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003200 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3201 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003202 break;
3203 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003204 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003205 }
3206}
3207
Mathias Agopiane57f2922012-08-09 16:29:12 -07003208uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3209{
Jesse Hall9a143922012-10-04 16:29:19 -07003210 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3211 if (dpyIdx < 0)
3212 return 0;
3213
Mathias Agopiane57f2922012-08-09 16:29:12 -07003214 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003215 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003216 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003217 const uint32_t what = s.what;
3218 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003219 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003220 disp.surface = s.surface;
3221 flags |= eDisplayTransactionNeeded;
3222 }
3223 }
3224 if (what & DisplayState::eLayerStackChanged) {
3225 if (disp.layerStack != s.layerStack) {
3226 disp.layerStack = s.layerStack;
3227 flags |= eDisplayTransactionNeeded;
3228 }
3229 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003230 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003231 if (disp.orientation != s.orientation) {
3232 disp.orientation = s.orientation;
3233 flags |= eDisplayTransactionNeeded;
3234 }
3235 if (disp.frame != s.frame) {
3236 disp.frame = s.frame;
3237 flags |= eDisplayTransactionNeeded;
3238 }
3239 if (disp.viewport != s.viewport) {
3240 disp.viewport = s.viewport;
3241 flags |= eDisplayTransactionNeeded;
3242 }
3243 }
Michael Lentine47e45402014-07-18 15:34:25 -07003244 if (what & DisplayState::eDisplaySizeChanged) {
3245 if (disp.width != s.width) {
3246 disp.width = s.width;
3247 flags |= eDisplayTransactionNeeded;
3248 }
3249 if (disp.height != s.height) {
3250 disp.height = s.height;
3251 flags |= eDisplayTransactionNeeded;
3252 }
3253 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003254 }
3255 return flags;
3256}
3257
chaviwca27f252018-02-06 16:46:39 -08003258uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3259 const layer_state_t& s = composerState.state;
3260 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3261
Mathias Agopian13127d82013-03-05 17:47:11 -08003262 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003263 if (layer == nullptr) {
3264 return 0;
3265 }
3266
3267 if (layer->isPendingRemoval()) {
3268 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3269 return 0;
3270 }
3271
3272 uint32_t flags = 0;
3273
3274 const uint32_t what = s.what;
3275 bool geometryAppliesWithResize =
3276 what & layer_state_t::eGeometryAppliesWithResize;
3277 if (what & layer_state_t::ePositionChanged) {
3278 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3279 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003280 }
chaviw8b3871a2017-11-01 17:41:01 -07003281 }
3282 if (what & layer_state_t::eLayerChanged) {
3283 // NOTE: index needs to be calculated before we update the state
3284 const auto& p = layer->getParent();
3285 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003286 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003287 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003288 mCurrentState.layersSortedByZ.removeAt(idx);
3289 mCurrentState.layersSortedByZ.add(layer);
3290 // we need traversal (state changed)
3291 // AND transaction (list changed)
3292 flags |= eTransactionNeeded|eTraversalNeeded;
3293 }
chaviw8b3871a2017-11-01 17:41:01 -07003294 } else {
3295 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003296 flags |= eTransactionNeeded|eTraversalNeeded;
3297 }
3298 }
chaviw8b3871a2017-11-01 17:41:01 -07003299 }
3300 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003301 // NOTE: index needs to be calculated before we update the state
3302 const auto& p = layer->getParent();
3303 if (p == nullptr) {
3304 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3305 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3306 mCurrentState.layersSortedByZ.removeAt(idx);
3307 mCurrentState.layersSortedByZ.add(layer);
3308 // we need traversal (state changed)
3309 // AND transaction (list changed)
3310 flags |= eTransactionNeeded|eTraversalNeeded;
3311 }
3312 } else {
3313 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3314 flags |= eTransactionNeeded|eTraversalNeeded;
3315 }
chaviw8b3871a2017-11-01 17:41:01 -07003316 }
3317 }
3318 if (what & layer_state_t::eSizeChanged) {
3319 if (layer->setSize(s.w, s.h)) {
3320 flags |= eTraversalNeeded;
3321 }
3322 }
3323 if (what & layer_state_t::eAlphaChanged) {
3324 if (layer->setAlpha(s.alpha))
3325 flags |= eTraversalNeeded;
3326 }
3327 if (what & layer_state_t::eColorChanged) {
3328 if (layer->setColor(s.color))
3329 flags |= eTraversalNeeded;
3330 }
3331 if (what & layer_state_t::eMatrixChanged) {
3332 if (layer->setMatrix(s.matrix))
3333 flags |= eTraversalNeeded;
3334 }
3335 if (what & layer_state_t::eTransparentRegionChanged) {
3336 if (layer->setTransparentRegionHint(s.transparentRegion))
3337 flags |= eTraversalNeeded;
3338 }
3339 if (what & layer_state_t::eFlagsChanged) {
3340 if (layer->setFlags(s.flags, s.mask))
3341 flags |= eTraversalNeeded;
3342 }
3343 if (what & layer_state_t::eCropChanged) {
3344 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3345 flags |= eTraversalNeeded;
3346 }
3347 if (what & layer_state_t::eFinalCropChanged) {
3348 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3349 flags |= eTraversalNeeded;
3350 }
3351 if (what & layer_state_t::eLayerStackChanged) {
3352 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3353 // We only allow setting layer stacks for top level layers,
3354 // everything else inherits layer stack from its parent.
3355 if (layer->hasParent()) {
3356 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3357 layer->getName().string());
3358 } else if (idx < 0) {
3359 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3360 "that also does not appear in the top level layer list. Something"
3361 " has gone wrong.", layer->getName().string());
3362 } else if (layer->setLayerStack(s.layerStack)) {
3363 mCurrentState.layersSortedByZ.removeAt(idx);
3364 mCurrentState.layersSortedByZ.add(layer);
3365 // we need traversal (state changed)
3366 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003367 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003368 }
3369 }
3370 if (what & layer_state_t::eDeferTransaction) {
3371 if (s.barrierHandle != nullptr) {
3372 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3373 } else if (s.barrierGbp != nullptr) {
3374 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3375 if (authenticateSurfaceTextureLocked(gbp)) {
3376 const auto& otherLayer =
3377 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3378 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3379 } else {
3380 ALOGE("Attempt to defer transaction to to an"
3381 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003382 }
3383 }
chaviw8b3871a2017-11-01 17:41:01 -07003384 // We don't trigger a traversal here because if no other state is
3385 // changed, we don't want this to cause any more work
3386 }
3387 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003388 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003389 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003390 if (!hadParent) {
3391 mCurrentState.layersSortedByZ.remove(layer);
3392 }
chaviw8b3871a2017-11-01 17:41:01 -07003393 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003394 }
chaviw8b3871a2017-11-01 17:41:01 -07003395 }
3396 if (what & layer_state_t::eReparentChildren) {
3397 if (layer->reparentChildren(s.reparentHandle)) {
3398 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003399 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003400 }
chaviw8b3871a2017-11-01 17:41:01 -07003401 if (what & layer_state_t::eDetachChildren) {
3402 layer->detachChildren();
3403 }
3404 if (what & layer_state_t::eOverrideScalingModeChanged) {
3405 layer->setOverrideScalingMode(s.overrideScalingMode);
3406 // We don't trigger a traversal here because if no other state is
3407 // changed, we don't want this to cause any more work
3408 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003409 return flags;
3410}
3411
chaviwca27f252018-02-06 16:46:39 -08003412void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3413 const layer_state_t& state = composerState.state;
3414 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3415
3416 sp<Layer> layer(client->getLayerUser(state.surface));
3417 if (layer == nullptr) {
3418 return;
3419 }
3420
3421 if (layer->isPendingRemoval()) {
3422 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3423 return;
3424 }
3425
3426 if (state.what & layer_state_t::eDestroySurface) {
3427 removeLayerLocked(mStateLock, layer);
3428 }
3429}
3430
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003431status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003432 const String8& name,
3433 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003434 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003435 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003436 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003437{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003438 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003439 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003440 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003441 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003442 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003443
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003444 status_t result = NO_ERROR;
3445
3446 sp<Layer> layer;
3447
Cody Northropbc755282017-03-31 12:00:08 -06003448 String8 uniqueName = getUniqueLayerName(name);
3449
Mathias Agopian3165cc22012-08-08 19:42:09 -07003450 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3451 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003452 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003453 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003454 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003455
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003456 break;
chaviw13fdc492017-06-27 12:40:18 -07003457 case ISurfaceComposerClient::eFXSurfaceColor:
3458 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003459 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003460 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003461 break;
3462 default:
3463 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003464 break;
3465 }
3466
Dan Stoza7d89d062015-04-30 13:29:25 -07003467 if (result != NO_ERROR) {
3468 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003469 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003470
Chia-I Wuab0c3192017-08-01 11:29:00 -07003471 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3472 // TODO b/64227542
3473 if (windowType == 441731) {
3474 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3475 layer->setPrimaryDisplayOnly();
3476 }
3477
Albert Chaulk479c60c2017-01-27 14:21:34 -05003478 layer->setInfo(windowType, ownerUid);
3479
Robert Carr1f0a16a2016-10-24 16:27:39 -07003480 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003481 if (result != NO_ERROR) {
3482 return result;
3483 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003484 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003485
3486 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003487 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003488}
3489
Cody Northropbc755282017-03-31 12:00:08 -06003490String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3491{
3492 bool matchFound = true;
3493 uint32_t dupeCounter = 0;
3494
3495 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3496 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3497
3498 // Loop over layers until we're sure there is no matching name
3499 while (matchFound) {
3500 matchFound = false;
3501 mDrawingState.traverseInZOrder([&](Layer* layer) {
3502 if (layer->getName() == uniqueName) {
3503 matchFound = true;
3504 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3505 }
3506 });
3507 }
3508
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003509 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3510 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003511
3512 return uniqueName;
3513}
3514
David Sodman0c69cad2017-08-21 12:12:51 -07003515status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003516 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3517 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003518{
3519 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003520 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 case PIXEL_FORMAT_TRANSPARENT:
3522 case PIXEL_FORMAT_TRANSLUCENT:
3523 format = PIXEL_FORMAT_RGBA_8888;
3524 break;
3525 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003526 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003527 break;
3528 }
3529
David Sodman0c69cad2017-08-21 12:12:51 -07003530 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3531 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003532 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003533 *handle = layer->getHandle();
3534 *gbp = layer->getProducer();
3535 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003536 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003537
David Sodman0c69cad2017-08-21 12:12:51 -07003538 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003539 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003540}
3541
chaviw13fdc492017-06-27 12:40:18 -07003542status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003543 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003544 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003545{
chaviw13fdc492017-06-27 12:40:18 -07003546 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003547 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003548 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003549}
3550
Mathias Agopianac9fa422013-02-11 16:40:36 -08003551status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003552{
Robert Carr9524cb32017-02-13 11:32:32 -08003553 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003554 status_t err = NO_ERROR;
3555 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003556 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003557 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003558 err = removeLayer(l);
3559 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3560 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003561 }
3562 return err;
3563}
3564
Mathias Agopian13127d82013-03-05 17:47:11 -08003565status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003566{
Mathias Agopian67106042013-03-14 19:18:13 -07003567 // called by ~LayerCleaner() when all references to the IBinder (handle)
3568 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003569 sp<Layer> l = layer.promote();
3570 if (l == nullptr) {
3571 // The layer has already been removed, carry on
3572 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003573 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003574 // If we have a parent, then we can continue to live as long as it does.
3575 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576}
3577
Mathias Agopianb60314a2012-04-10 22:09:54 -07003578// ---------------------------------------------------------------------------
3579
Andy McFadden13a082e2012-08-24 10:16:42 -07003580void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003581 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003582 Vector<ComposerState> state;
3583 Vector<DisplayState> displays;
3584 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003585 d.what = DisplayState::eDisplayProjectionChanged |
3586 DisplayState::eLayerStackChanged;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003587 d.token = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003588 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003589 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003590 d.frame.makeInvalid();
3591 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003592 d.width = 0;
3593 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003594 displays.add(d);
3595 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003596 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3597 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003598
David Sodman105b7dc2017-11-04 20:28:14 -07003599 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003600 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003601 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003602
Brian Andersond0010582017-03-07 13:20:31 -08003603 // Use phase of 0 since phase is not known.
3604 // Use latency of 0, which will snap to the ideal latency.
3605 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003606}
3607
3608void SurfaceFlinger::initializeDisplays() {
3609 class MessageScreenInitialized : public MessageBase {
3610 SurfaceFlinger* flinger;
3611 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003612 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003613 virtual bool handler() {
3614 flinger->onInitializeDisplays();
3615 return true;
3616 }
3617 };
3618 sp<MessageBase> msg = new MessageScreenInitialized(this);
3619 postMessageAsync(msg); // we may be called from main thread, use async message
3620}
3621
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003622void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3623 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003624 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003625 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003626
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003627 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003628 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003629 return;
3630 }
3631
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003632 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003633 ALOGW("Trying to set power mode for virtual display");
3634 return;
3635 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003636
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003637 display->setPowerMode(mode);
3638
Lloyd Pique4dccc412018-01-22 17:21:36 -08003639 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003640 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003641 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003642 if (idx < 0) {
3643 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3644 return;
3645 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003646 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003647 }
3648
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003649 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003650 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003651 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003652 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003653 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003654 // FIXME: eventthread only knows about the main display right now
3655 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003656 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003658
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003659 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003660 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003661 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003662
3663 struct sched_param param = {0};
3664 param.sched_priority = 1;
3665 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3666 ALOGW("Couldn't set SCHED_FIFO on display on");
3667 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003668 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003669 // Turn off the display
3670 struct sched_param param = {0};
3671 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3672 ALOGW("Couldn't set SCHED_OTHER on display off");
3673 }
3674
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003675 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003676 disableHardwareVsync(true); // also cancels any in-progress resync
3677
Mathias Agopiancde87a32012-09-13 14:09:01 -07003678 // FIXME: eventthread only knows about the main display right now
3679 mEventThread->onScreenReleased();
3680 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003681
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003682 getHwComposer().setPowerMode(type, mode);
3683 mVisibleRegionsDirty = true;
3684 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003685 } else if (mode == HWC_POWER_MODE_DOZE ||
3686 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003687 // Update display while dozing
3688 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003689 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003690 // FIXME: eventthread only knows about the main display right now
3691 mEventThread->onScreenAcquired();
3692 resyncToHardwareVsync(true);
3693 }
3694 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3695 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003696 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003697 disableHardwareVsync(true); // also cancels any in-progress resync
3698 // FIXME: eventthread only knows about the main display right now
3699 mEventThread->onScreenReleased();
3700 }
3701 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003702 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003703 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003704 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003705 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003706
3707 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003708}
3709
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003710void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
3711 postMessageSync(new LambdaMessage([&]() {
3712 const auto display = getDisplayDevice(displayToken);
3713 if (!display) {
3714 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3715 displayToken.get());
3716 } else if (display->isVirtual()) {
3717 ALOGW("Attempt to set power mode %d for virtual display", mode);
3718 } else {
3719 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003720 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003721 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003722}
3723
3724// ---------------------------------------------------------------------------
3725
Lloyd Pique755e3192018-01-31 16:46:15 -08003726status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3727 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003728 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003729
Mathias Agopianbd115332013-04-18 16:41:04 -07003730 IPCThreadState* ipc = IPCThreadState::self();
3731 const int pid = ipc->getCallingPid();
3732 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003733
Mathias Agopianbd115332013-04-18 16:41:04 -07003734 if ((uid != AID_SHELL) &&
3735 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003736 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003737 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003738 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003739 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003740 // (this would indicate SF is stuck, but we want to be able to
3741 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003742 status_t err = mStateLock.timedLock(s2ns(1));
3743 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003744 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003745 result.appendFormat(
3746 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3747 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003748 }
3749
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003750 bool dumpAll = true;
3751 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003752 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003753
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003754 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003755 if ((index < numArgs) &&
3756 (args[index] == String16("--list"))) {
3757 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003758 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003759 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003760 }
3761
3762 if ((index < numArgs) &&
3763 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003764 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003765 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003766 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003767 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003768
3769 if ((index < numArgs) &&
3770 (args[index] == String16("--latency-clear"))) {
3771 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003772 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003773 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003774 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003775
3776 if ((index < numArgs) &&
3777 (args[index] == String16("--dispsync"))) {
3778 index++;
3779 mPrimaryDispSync.dump(result);
3780 dumpAll = false;
3781 }
Dan Stozab90cf072015-03-05 11:05:59 -08003782
3783 if ((index < numArgs) &&
3784 (args[index] == String16("--static-screen"))) {
3785 index++;
3786 dumpStaticScreenStats(result);
3787 dumpAll = false;
3788 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003789
3790 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003791 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003792 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003793 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003794 dumpAll = false;
3795 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003796
3797 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3798 index++;
3799 dumpWideColorInfo(result);
3800 dumpAll = false;
3801 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003802
3803 if ((index < numArgs) &&
3804 (args[index] == String16("--enable-layer-stats"))) {
3805 index++;
3806 mLayerStats.enable();
3807 dumpAll = false;
3808 }
3809
3810 if ((index < numArgs) &&
3811 (args[index] == String16("--disable-layer-stats"))) {
3812 index++;
3813 mLayerStats.disable();
3814 dumpAll = false;
3815 }
3816
3817 if ((index < numArgs) &&
3818 (args[index] == String16("--clear-layer-stats"))) {
3819 index++;
3820 mLayerStats.clear();
3821 dumpAll = false;
3822 }
3823
3824 if ((index < numArgs) &&
3825 (args[index] == String16("--dump-layer-stats"))) {
3826 index++;
3827 mLayerStats.dump(result);
3828 dumpAll = false;
3829 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003830
3831 if ((index < numArgs) &&
3832 (args[index] == String16("--display-identification"))) {
3833 index++;
3834 dumpDisplayIdentificationData(result);
3835 dumpAll = false;
3836 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003837
3838 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3839 index++;
3840 mTimeStats.parseArgs(asProto, args, index, result);
3841 dumpAll = false;
3842 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003843 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003844
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003845 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003846 if (asProto) {
3847 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3848 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3849 } else {
3850 dumpAllLocked(args, index, result);
3851 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003852 }
3853
Mathias Agopian9795c422009-08-26 16:36:26 -07003854 if (locked) {
3855 mStateLock.unlock();
3856 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003857 }
3858 write(fd, result.string(), result.size());
3859 return NO_ERROR;
3860}
3861
Dan Stozac7014012014-02-14 15:03:43 -08003862void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3863 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003864{
Robert Carr2047fae2016-11-28 14:09:09 -08003865 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003866 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003867 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003868}
3869
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003870void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003871 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003872{
3873 String8 name;
3874 if (index < args.size()) {
3875 name = String8(args[index]);
3876 index++;
3877 }
3878
David Sodman105b7dc2017-11-04 20:28:14 -07003879 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003880 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003881 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003882
3883 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003884 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003885 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003886 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003887 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003888 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003889 }
Robert Carr2047fae2016-11-28 14:09:09 -08003890 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003891 }
3892}
3893
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003894void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003895 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003896{
3897 String8 name;
3898 if (index < args.size()) {
3899 name = String8(args[index]);
3900 index++;
3901 }
3902
Robert Carr2047fae2016-11-28 14:09:09 -08003903 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003904 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003905 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003906 }
Robert Carr2047fae2016-11-28 14:09:09 -08003907 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003908
Svetoslavd85084b2014-03-20 10:28:31 -07003909 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003910}
3911
Jamie Gennis6547ff42013-07-16 20:12:42 -07003912// This should only be called from the main thread. Otherwise it would need
3913// the lock and should use mCurrentState rather than mDrawingState.
3914void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003915 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003916 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003917 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003918
3919 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3920}
3921
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003922void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003923{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003924 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003925
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003926 if (isLayerTripleBufferingDisabled())
3927 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003928
3929 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003930 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003931 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003932 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003933 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3934 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003935 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003936}
3937
Dan Stozab90cf072015-03-05 11:05:59 -08003938void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3939{
3940 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003941 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3942 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003943 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003944 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003945 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3946 b + 1, bucketTimeSec, percent);
3947 }
David Sodman4a36e932017-11-07 14:29:47 -08003948 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003949 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003950 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003951 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003952 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003953}
3954
Dan Stozae77c7662016-05-13 11:37:28 -07003955void SurfaceFlinger::recordBufferingStats(const char* layerName,
3956 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003957 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3958 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003959 for (const auto& segment : history) {
3960 if (!segment.usedThirdBuffer) {
3961 stats.twoBufferTime += segment.totalTime;
3962 }
3963 if (segment.occupancyAverage < 1.0f) {
3964 stats.doubleBufferedTime += segment.totalTime;
3965 } else if (segment.occupancyAverage < 2.0f) {
3966 stats.tripleBufferedTime += segment.totalTime;
3967 }
3968 ++stats.numSegments;
3969 stats.totalTime += segment.totalTime;
3970 }
3971}
3972
Brian Andersond6927fb2016-07-23 23:37:30 -07003973void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3974 result.appendFormat("Layer frame timestamps:\n");
3975
3976 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3977 const size_t count = currentLayers.size();
3978 for (size_t i=0 ; i<count ; i++) {
3979 currentLayers[i]->dumpFrameEvents(result);
3980 }
3981}
3982
Dan Stozae77c7662016-05-13 11:37:28 -07003983void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3984 result.append("Buffering stats:\n");
3985 result.append(" [Layer name] <Active time> <Two buffer> "
3986 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003987 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003988 typedef std::tuple<std::string, float, float, float> BufferTuple;
3989 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003990 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003991 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003992 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003993 if (stats.numSegments == 0) {
3994 continue;
3995 }
3996 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3997 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3998 stats.totalTime;
3999 float doubleBufferRatio = static_cast<float>(
4000 stats.doubleBufferedTime) / stats.totalTime;
4001 float tripleBufferRatio = static_cast<float>(
4002 stats.tripleBufferedTime) / stats.totalTime;
4003 sorted.insert({activeTime, {name, twoBufferRatio,
4004 doubleBufferRatio, tripleBufferRatio}});
4005 }
4006 for (const auto& sortedPair : sorted) {
4007 float activeTime = sortedPair.first;
4008 const BufferTuple& values = sortedPair.second;
4009 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4010 std::get<0>(values).c_str(), activeTime,
4011 std::get<1>(values), std::get<2>(values),
4012 std::get<3>(values));
4013 }
4014 result.append("\n");
4015}
4016
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004017void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004018 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004019 const int32_t displayId = display->getId();
4020 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4021 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004022 continue;
4023 }
4024
Dominik Laskowski7e045462018-05-30 13:02:02 -07004025 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004026 uint8_t port;
4027 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004028 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004029 result.append("no identification data\n");
4030 continue;
4031 }
4032
4033 if (!isEdid(data)) {
4034 result.append("unknown identification data: ");
4035 for (uint8_t byte : data) {
4036 result.appendFormat("%x ", byte);
4037 }
4038 result.append("\n");
4039 continue;
4040 }
4041
4042 const auto edid = parseEdid(data);
4043 if (!edid) {
4044 result.append("invalid EDID: ");
4045 for (uint8_t byte : data) {
4046 result.appendFormat("%x ", byte);
4047 }
4048 result.append("\n");
4049 continue;
4050 }
4051
4052 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4053 result.append(edid->displayName.data(), edid->displayName.length());
4054 result.append("\"\n");
4055 }
4056 result.append("\n");
4057}
4058
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004059void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4060 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004061 result.appendFormat("DisplayColorSetting: %s\n",
4062 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004063
4064 // TODO: print out if wide-color mode is active or not
4065
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004066 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004067 const int32_t displayId = display->getId();
4068 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004069 continue;
4070 }
4071
Dominik Laskowski7e045462018-05-30 13:02:02 -07004072 result.appendFormat("Display %d color modes:\n", displayId);
4073 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004074 for (auto&& mode : modes) {
4075 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4076 }
4077
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004078 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004079 result.appendFormat(" Current color mode: %s (%d)\n",
4080 decodeColorMode(currentMode).c_str(), currentMode);
4081 }
4082 result.append("\n");
4083}
4084
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004085LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004086 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004087 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4088 const State& state = useDrawing ? mDrawingState : mCurrentState;
4089 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004090 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004091 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004092 });
4093
4094 return layersProto;
4095}
4096
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004097LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004098 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004099
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004100 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004101 resolution->set_w(display.getWidth());
4102 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004103
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004104 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4105 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4106 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004107
Dominik Laskowski7e045462018-05-30 13:02:02 -07004108 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004109 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004110 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004111 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004112 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004113 }
4114 });
4115
4116 return layersProto;
4117}
4118
Mathias Agopian74d211a2013-04-22 16:55:35 +02004119void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4120 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004121{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004122 bool colorize = false;
4123 if (index < args.size()
4124 && (args[index] == String16("--color"))) {
4125 colorize = true;
4126 index++;
4127 }
4128
4129 Colorizer colorizer(colorize);
4130
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004131 // figure out if we're stuck somewhere
4132 const nsecs_t now = systemTime();
4133 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4134 const nsecs_t inTransaction(mDebugInTransaction);
4135 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4136 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4137
4138 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004139 * Dump library configuration.
4140 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004141
4142 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004143 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004144 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004145 appendSfConfigString(result);
4146 appendUiConfigString(result);
4147 appendGuiConfigString(result);
4148 result.append("\n");
4149
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004150 result.append("\nDisplay identification data:\n");
4151 dumpDisplayIdentificationData(result);
4152
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004153 result.append("\nWide-Color information:\n");
4154 dumpWideColorInfo(result);
4155
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004156 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004157 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004158 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004159 result.append(SyncFeatures::getInstance().toString());
4160 result.append("\n");
4161
David Sodman105b7dc2017-11-04 20:28:14 -07004162 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004163
Andy McFadden41d67d72014-04-25 16:58:34 -07004164 colorizer.bold(result);
4165 result.append("DispSync configuration: ");
4166 colorizer.reset(result);
Dan Stoza84d619e2018-03-28 17:07:36 -07004167 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4168 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4169 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004170 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004171 result.append("\n");
4172
Dan Stozab90cf072015-03-05 11:05:59 -08004173 // Dump static screen stats
4174 result.append("\n");
4175 dumpStaticScreenStats(result);
4176 result.append("\n");
4177
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004178 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4179
Dan Stozae77c7662016-05-13 11:37:28 -07004180 dumpBufferingStats(result);
4181
Andy McFadden4803b742012-09-24 19:07:20 -07004182 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004183 * Dump the visible layer list
4184 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004185 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004186 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004187 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4188 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004189 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004190
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004191 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004192 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004193 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004194 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004195
4196 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004197 * Dump Display state
4198 */
4199
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004200 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004201 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004202 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004203 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004204 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004205 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004206 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004207
4208 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004209 * Dump SurfaceFlinger global state
4210 */
4211
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004212 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004213 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004214 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004215
Mathias Agopian888c8222012-08-04 21:10:38 -07004216 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004217 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004218
David Sodmanbc815282017-11-05 18:57:52 -08004219 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004220
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004221 if (display) {
4222 display->undefinedRegion.dump(result, "undefinedRegion");
4223 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4224 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004225 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004226 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004227 " last eglSwapBuffers() time: %f us\n"
4228 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004229 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004230 " refresh-rate : %f fps\n"
4231 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004232 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004233 " gpu_to_cpu_unsupported : %d\n"
4234 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004235 mLastSwapBufferTime/1000.0,
4236 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004237 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004238 1e9 / activeConfig->getVsyncPeriod(),
4239 activeConfig->getDpiX(),
4240 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004241 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004242
Mathias Agopian74d211a2013-04-22 16:55:35 +02004243 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004244 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004245
Mathias Agopian74d211a2013-04-22 16:55:35 +02004246 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004247 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004248
4249 /*
4250 * VSYNC state
4251 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004252 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004253 result.append("\n");
4254
4255 /*
4256 * HWC layer minidump
4257 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004258 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004259 const int32_t displayId = display->getId();
4260 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004261 continue;
4262 }
4263
Dominik Laskowski7e045462018-05-30 13:02:02 -07004264 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004265 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004266 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004267 result.append("\n");
4268 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004269
4270 /*
4271 * Dump HWComposer state
4272 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004273 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004274 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004275 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004276 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004277 result.appendFormat(" h/w composer %s\n",
4278 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004279 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004280
4281 /*
4282 * Dump gralloc state
4283 */
4284 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4285 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004286
4287 /*
4288 * Dump VrFlinger state if in use.
4289 */
4290 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4291 result.append("VrFlinger state:\n");
4292 result.append(mVrFlinger->Dump().c_str());
4293 result.append("\n");
4294 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004295}
4296
Dominik Laskowski7e045462018-05-30 13:02:02 -07004297const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004298 // Note: mStateLock is held here
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004299 wp<IBinder> displayToken;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004300 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004301 if (display->getId() == displayId) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004302 displayToken = token;
Jesse Hall48bc05b2013-03-21 14:06:52 -07004303 break;
4304 }
4305 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004306 if (displayToken == nullptr) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004307 ALOGE("getLayerSortedByZForHwcDisplay: Invalid display %d", displayId);
Jesse Hall48bc05b2013-03-21 14:06:52 -07004308 // Just use the primary display so we have something to return
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004309 displayToken = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
Jesse Hall48bc05b2013-03-21 14:06:52 -07004310 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004311 return getDisplayDeviceLocked(displayToken)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004312}
4313
Keun young Park63f165f2012-08-31 10:53:36 -07004314bool SurfaceFlinger::startDdmConnection()
4315{
4316 void* libddmconnection_dso =
4317 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4318 if (!libddmconnection_dso) {
4319 return false;
4320 }
4321 void (*DdmConnection_start)(const char* name);
4322 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004323 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004324 if (!DdmConnection_start) {
4325 dlclose(libddmconnection_dso);
4326 return false;
4327 }
4328 (*DdmConnection_start)(getServiceName());
4329 return true;
4330}
4331
Chia-I Wu28f320b2018-05-03 11:02:56 -07004332void SurfaceFlinger::updateColorMatrixLocked() {
4333 mat4 colorMatrix;
4334 if (mGlobalSaturationFactor != 1.0f) {
4335 // Rec.709 luma coefficients
4336 float3 luminance{0.213f, 0.715f, 0.072f};
4337 luminance *= 1.0f - mGlobalSaturationFactor;
4338 mat4 saturationMatrix = mat4(
4339 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4340 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4341 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4342 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4343 );
4344 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4345 } else {
4346 colorMatrix = mClientColorMatrix * mDaltonizer();
4347 }
4348
4349 if (mCurrentState.colorMatrix != colorMatrix) {
4350 mCurrentState.colorMatrix = colorMatrix;
4351 mCurrentState.colorMatrixChanged = true;
4352 setTransactionFlags(eTransactionNeeded);
4353 }
4354}
4355
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004356status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004357 switch (code) {
4358 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004359 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004360 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004361 case CLEAR_ANIMATION_FRAME_STATS:
4362 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004363 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004364 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004365 case ENABLE_VSYNC_INJECTIONS:
4366 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004367 {
4368 // codes that require permission check
4369 IPCThreadState* ipc = IPCThreadState::self();
4370 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004371 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004372 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004373 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004374 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004375 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004376 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004377 break;
4378 }
Robert Carr1db73f62016-12-21 12:58:51 -08004379 /*
4380 * Calling setTransactionState is safe, because you need to have been
4381 * granted a reference to Client* and Handle* to do anything with it.
4382 *
4383 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4384 */
4385 case SET_TRANSACTION_STATE:
4386 case CREATE_SCOPED_CONNECTION:
4387 {
4388 return OK;
4389 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004390 case CAPTURE_SCREEN:
4391 {
4392 // codes that require permission check
4393 IPCThreadState* ipc = IPCThreadState::self();
4394 const int pid = ipc->getCallingPid();
4395 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004396 if ((uid != AID_GRAPHICS) &&
4397 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004398 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004399 return PERMISSION_DENIED;
4400 }
4401 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004402 }
chaviwa76b2712017-09-20 12:02:26 -07004403 case CAPTURE_LAYERS: {
4404 IPCThreadState* ipc = IPCThreadState::self();
4405 const int pid = ipc->getCallingPid();
4406 const int uid = ipc->getCallingUid();
4407 if ((uid != AID_GRAPHICS) &&
4408 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4409 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4410 return PERMISSION_DENIED;
4411 }
4412 break;
4413 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004414 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004415 return OK;
4416}
4417
4418status_t SurfaceFlinger::onTransact(
4419 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4420{
4421 status_t credentialCheck = CheckTransactCodeCredentials(code);
4422 if (credentialCheck != OK) {
4423 return credentialCheck;
4424 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004425
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004426 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4427 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004428 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004429 IPCThreadState* ipc = IPCThreadState::self();
4430 const int uid = ipc->getCallingUid();
4431 if (CC_UNLIKELY(uid != AID_SYSTEM
4432 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004433 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004434 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004435 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004436 return PERMISSION_DENIED;
4437 }
4438 int n;
4439 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004440 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004441 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004442 return NO_ERROR;
4443 case 1002: // SHOW_UPDATES
4444 n = data.readInt32();
4445 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004446 invalidateHwcGeometry();
4447 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004448 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004449 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004450 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004451 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004452 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004453 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004454 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004455 setTransactionFlags(
4456 eTransactionNeeded|
4457 eDisplayTransactionNeeded|
4458 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004459 return NO_ERROR;
4460 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004461 case 1006:{ // send empty update
4462 signalRefresh();
4463 return NO_ERROR;
4464 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004465 case 1008: // toggle use of hw composer
4466 n = data.readInt32();
4467 mDebugDisableHWC = n ? 1 : 0;
4468 invalidateHwcGeometry();
4469 repaintEverything();
4470 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004471 case 1009: // toggle use of transform hint
4472 n = data.readInt32();
4473 mDebugDisableTransformHint = n ? 1 : 0;
4474 invalidateHwcGeometry();
4475 repaintEverything();
4476 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004477 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004478 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004479 reply->writeInt32(0);
4480 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004481 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004482 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004483 return NO_ERROR;
4484 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004485 const auto display = getDefaultDisplayDevice();
4486 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004487 return NO_ERROR;
4488 }
4489 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004490 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004491 // daltonize
4492 n = data.readInt32();
4493 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004494 case 1:
4495 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4496 break;
4497 case 2:
4498 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4499 break;
4500 case 3:
4501 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4502 break;
4503 default:
4504 mDaltonizer.setType(ColorBlindnessType::None);
4505 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004506 }
4507 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004508 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004509 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004510 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004511 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004512
4513 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004514 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004515 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004516 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004517 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004518 // apply a color matrix
4519 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004520 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004521 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004522 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004523 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004524 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004525 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004526 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004527 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004528 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004529 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004530
4531 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4532 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004533 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004534 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4535 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4536 }
4537
Chia-I Wu28f320b2018-05-03 11:02:56 -07004538 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004539 return NO_ERROR;
4540 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004541 // This is an experimental interface
4542 // Needs to be shifted to proper binder interface when we productize
4543 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004544 n = data.readInt32();
4545 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004546 return NO_ERROR;
4547 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004548 case 1017: {
4549 n = data.readInt32();
4550 mForceFullDamage = static_cast<bool>(n);
4551 return NO_ERROR;
4552 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004553 case 1018: { // Modify Choreographer's phase offset
4554 n = data.readInt32();
4555 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4556 return NO_ERROR;
4557 }
4558 case 1019: { // Modify SurfaceFlinger's phase offset
4559 n = data.readInt32();
4560 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4561 return NO_ERROR;
4562 }
Irvel468051e2016-06-13 16:44:44 -07004563 case 1020: { // Layer updates interceptor
4564 n = data.readInt32();
4565 if (n) {
4566 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004567 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004568 }
4569 else{
4570 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004571 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004572 }
4573 return NO_ERROR;
4574 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004575 case 1021: { // Disable HWC virtual displays
4576 n = data.readInt32();
4577 mUseHwcVirtualDisplays = !n;
4578 return NO_ERROR;
4579 }
Romain Guy0147a172017-06-01 13:53:56 -07004580 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004581 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004582 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004583
Chia-I Wu28f320b2018-05-03 11:02:56 -07004584 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004585 return NO_ERROR;
4586 }
Romain Guy54f154a2017-10-24 21:40:32 +01004587 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004588 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004589 invalidateHwcGeometry();
4590 repaintEverything();
4591 return NO_ERROR;
4592 }
4593 case 1024: { // Is wide color gamut rendering/color management supported?
4594 reply->writeBool(hasWideColorDisplay);
4595 return NO_ERROR;
4596 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004597 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004598 n = data.readInt32();
4599 if (n) {
4600 ALOGV("LayerTracing enabled");
4601 mTracing.enable();
4602 doTracing("tracing.enable");
4603 reply->writeInt32(NO_ERROR);
4604 } else {
4605 ALOGV("LayerTracing disabled");
4606 status_t err = mTracing.disable();
4607 reply->writeInt32(err);
4608 }
4609 return NO_ERROR;
4610 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004611 case 1026: { // Get layer tracing status
4612 reply->writeBool(mTracing.isEnabled());
4613 return NO_ERROR;
4614 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004615 // Is a DisplayColorSetting supported?
4616 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004617 const auto display = getDefaultDisplayDevice();
4618 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004619 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004620 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004621
4622 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4623 switch (setting) {
4624 case DisplayColorSetting::MANAGED:
4625 reply->writeBool(hasWideColorDisplay);
4626 break;
4627 case DisplayColorSetting::UNMANAGED:
4628 reply->writeBool(true);
4629 break;
4630 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004631 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004632 break;
4633 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004634 reply->writeBool(
4635 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004636 break;
4637 }
4638 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004639 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004640 }
4641 }
4642 return err;
4643}
4644
Steven Thomas6d8110b2017-08-31 18:24:21 -07004645void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004646 android_atomic_or(1, &mRepaintEverything);
4647 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004648}
4649
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004650// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4651class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004652public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004653 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4654 ~WindowDisconnector() {
4655 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004656 }
4657
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004658private:
4659 ANativeWindow* mWindow;
4660 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004661};
4662
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004663status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4664 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4665 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4666 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004667 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004668 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004669
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004670 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004671
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004672 const auto display = getDisplayDeviceLocked(displayToken);
4673 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004674
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004675 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004676
4677 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004678 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004679 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004680}
4681
4682status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004683 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004684 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004685 ATRACE_CALL();
4686
4687 class LayerRenderArea : public RenderArea {
4688 public:
Robert Carr578038f2018-03-09 12:25:24 -08004689 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4690 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004691 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004692 mLayer(layer),
4693 mCrop(crop),
4694 mFlinger(flinger),
4695 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004696 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004697 Rect getBounds() const override {
4698 const Layer::State& layerState(mLayer->getDrawingState());
4699 return Rect(layerState.active.w, layerState.active.h);
4700 }
4701 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4702 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4703 bool isSecure() const override { return false; }
4704 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004705 Rect getSourceCrop() const override {
4706 if (mCrop.isEmpty()) {
4707 return getBounds();
4708 } else {
4709 return mCrop;
4710 }
4711 }
Robert Carr578038f2018-03-09 12:25:24 -08004712 class ReparentForDrawing {
4713 public:
4714 const sp<Layer>& oldParent;
4715 const sp<Layer>& newParent;
4716
4717 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4718 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004719 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004720 }
Robert Carr15eae092018-03-23 13:43:53 -07004721 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004722 };
4723
4724 void render(std::function<void()> drawLayers) override {
4725 if (!mChildrenOnly) {
4726 mTransform = mLayer->getTransform().inverse();
4727 drawLayers();
4728 } else {
4729 Rect bounds = getBounds();
4730 screenshotParentLayer =
4731 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4732 bounds.getWidth(), bounds.getHeight(), 0);
4733
4734 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4735 drawLayers();
4736 }
4737 }
chaviwa76b2712017-09-20 12:02:26 -07004738
chaviwa76b2712017-09-20 12:02:26 -07004739 private:
chaviw7206d492017-11-10 16:16:12 -08004740 const sp<Layer> mLayer;
4741 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004742
4743 // In the "childrenOnly" case we reparent the children to a screenshot
4744 // layer which has no properties set and which does not draw.
4745 sp<ContainerLayer> screenshotParentLayer;
4746 Transform mTransform;
4747
4748 SurfaceFlinger* mFlinger;
4749 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004750 };
4751
4752 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4753 auto parent = layerHandle->owner.promote();
4754
chaviw7206d492017-11-10 16:16:12 -08004755 if (parent == nullptr || parent->isPendingRemoval()) {
4756 ALOGE("captureLayers called with a removed parent");
4757 return NAME_NOT_FOUND;
4758 }
4759
Robert Carr578038f2018-03-09 12:25:24 -08004760 const int uid = IPCThreadState::self()->getCallingUid();
4761 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4762 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4763 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4764 return PERMISSION_DENIED;
4765 }
4766
chaviw7206d492017-11-10 16:16:12 -08004767 Rect crop(sourceCrop);
4768 if (sourceCrop.width() <= 0) {
4769 crop.left = 0;
4770 crop.right = parent->getCurrentState().active.w;
4771 }
4772
4773 if (sourceCrop.height() <= 0) {
4774 crop.top = 0;
4775 crop.bottom = parent->getCurrentState().active.h;
4776 }
4777
4778 int32_t reqWidth = crop.width() * frameScale;
4779 int32_t reqHeight = crop.height() * frameScale;
4780
Robert Carr578038f2018-03-09 12:25:24 -08004781 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004782
Robert Carr578038f2018-03-09 12:25:24 -08004783 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004784 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4785 if (!layer->isVisible()) {
4786 return;
Robert Carr578038f2018-03-09 12:25:24 -08004787 } else if (childrenOnly && layer == parent.get()) {
4788 return;
chaviwa76b2712017-09-20 12:02:26 -07004789 }
4790 visitor(layer);
4791 });
4792 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004793 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004794}
4795
4796status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4797 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004798 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004799 bool useIdentityTransform) {
4800 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004801
Iris Chang7501ed62018-04-30 14:45:42 +08004802 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004803
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004804 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4805 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4806 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4807 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004808
4809 // This mutex protects syncFd and captureResult for communication of the return values from the
4810 // main thread back to this Binder thread
4811 std::mutex captureMutex;
4812 std::condition_variable captureCondition;
4813 std::unique_lock<std::mutex> captureLock(captureMutex);
4814 int syncFd = -1;
4815 std::optional<status_t> captureResult;
4816
Robert Carr03480e22018-01-04 16:02:06 -08004817 const int uid = IPCThreadState::self()->getCallingUid();
4818 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4819
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004820 sp<LambdaMessage> message = new LambdaMessage([&]() {
4821 // If there is a refresh pending, bug out early and tell the binder thread to try again
4822 // after the refresh.
4823 if (mRefreshPending) {
4824 ATRACE_NAME("Skipping screenshot for now");
4825 std::unique_lock<std::mutex> captureLock(captureMutex);
4826 captureResult = std::make_optional<status_t>(EAGAIN);
4827 captureCondition.notify_one();
4828 return;
4829 }
4830
4831 status_t result = NO_ERROR;
4832 int fd = -1;
4833 {
4834 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004835 renderArea.render([&]() {
4836 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4837 useIdentityTransform, forSystem, &fd);
4838 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004839 }
4840
4841 {
4842 std::unique_lock<std::mutex> captureLock(captureMutex);
4843 syncFd = fd;
4844 captureResult = std::make_optional<status_t>(result);
4845 captureCondition.notify_one();
4846 }
4847 });
4848
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004849 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004850 if (result == NO_ERROR) {
4851 captureCondition.wait(captureLock, [&]() { return captureResult; });
4852 while (*captureResult == EAGAIN) {
4853 captureResult.reset();
4854 result = postMessageAsync(message);
4855 if (result != NO_ERROR) {
4856 return result;
4857 }
4858 captureCondition.wait(captureLock, [&]() { return captureResult; });
4859 }
4860 result = *captureResult;
4861 }
4862
4863 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004864 sync_wait(syncFd, -1);
4865 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004866 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004867
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004868 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004869}
4870
chaviwa76b2712017-09-20 12:02:26 -07004871void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4872 TraverseLayersFunction traverseLayers, bool yswap,
4873 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004874 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004875
Lloyd Pique144e1162017-12-20 16:44:52 -08004876 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004877
4878 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004879 const auto raWidth = renderArea.getWidth();
4880 const auto raHeight = renderArea.getHeight();
4881
4882 const auto reqWidth = renderArea.getReqWidth();
4883 const auto reqHeight = renderArea.getReqHeight();
4884 Rect sourceCrop = renderArea.getSourceCrop();
4885
Iris Chang7501ed62018-04-30 14:45:42 +08004886 bool filtering = false;
4887 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4888 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
4889 static_cast<int32_t>(reqHeight) != raWidth;
4890 } else {
4891 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4892 static_cast<int32_t>(reqHeight) != raHeight;
4893 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004894
Dan Stozac1879002014-05-22 15:59:05 -07004895 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004896 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004897 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004898 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08004899 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4900 Transform tr;
4901 uint32_t flags = 0x00;
4902 switch (mPrimaryDisplayOrientation) {
4903 case DisplayState::eOrientation90:
4904 flags = Transform::ROT_90;
4905 break;
4906 case DisplayState::eOrientation180:
4907 flags = Transform::ROT_180;
4908 break;
4909 case DisplayState::eOrientation270:
4910 flags = Transform::ROT_270;
4911 break;
4912 }
4913 tr.set(flags, raWidth, raHeight);
4914 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07004915 }
4916
4917 // ensure that sourceCrop is inside screen
4918 if (sourceCrop.left < 0) {
4919 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4920 }
chaviwa76b2712017-09-20 12:02:26 -07004921 if (sourceCrop.right > raWidth) {
4922 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004923 }
4924 if (sourceCrop.top < 0) {
4925 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4926 }
chaviwa76b2712017-09-20 12:02:26 -07004927 if (sourceCrop.bottom > raHeight) {
4928 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004929 }
4930
Chia-I Wu36574d92018-05-16 10:54:36 -07004931 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
4932 engine.setOutputDataSpace(Dataspace::SRGB);
4933 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07004934
Mathias Agopian180f10d2013-04-10 22:55:41 -07004935 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004936 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004937
Iris Chang7501ed62018-04-30 14:45:42 +08004938 Transform::orientation_flags rotation = renderArea.getRotationFlags();
4939 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4940 // convert hw orientation into flag presentation
4941 // here inverse transform needed
4942 uint8_t hw_rot_90 = 0x00;
4943 uint8_t hw_flip_hv = 0x00;
4944 switch (mPrimaryDisplayOrientation) {
4945 case DisplayState::eOrientation90:
4946 hw_rot_90 = Transform::ROT_90;
4947 hw_flip_hv = Transform::ROT_180;
4948 break;
4949 case DisplayState::eOrientation180:
4950 hw_flip_hv = Transform::ROT_180;
4951 break;
4952 case DisplayState::eOrientation270:
4953 hw_rot_90 = Transform::ROT_90;
4954 break;
4955 }
4956
4957 // transform flags operation
4958 // 1) flip H V if both have ROT_90 flag
4959 // 2) XOR these flags
4960 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
4961 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
4962 if (rotation_rot_90 & hw_rot_90) {
4963 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
4964 }
4965 rotation = static_cast<Transform::orientation_flags>
4966 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
4967 }
4968
Mathias Agopian180f10d2013-04-10 22:55:41 -07004969 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004970 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08004971 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004972 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004973
chaviw50da5042018-04-09 13:49:37 -07004974 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004975 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004976 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004977
chaviwa76b2712017-09-20 12:02:26 -07004978 traverseLayers([&](Layer* layer) {
4979 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07004980 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004981 if (filtering) layer->setFiltering(false);
4982 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004983}
4984
chaviwa76b2712017-09-20 12:02:26 -07004985status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4986 TraverseLayersFunction traverseLayers,
4987 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004988 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004989 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004990 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004991 ATRACE_CALL();
4992
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004993 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004994
4995 traverseLayers([&](Layer* layer) {
4996 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4997 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004998
Robert Carr03480e22018-01-04 16:02:06 -08004999 // We allow the system server to take screenshots of secure layers for
5000 // use in situations like the Screen-rotation animation and place
5001 // the impetus on WindowManager to not persist them.
5002 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005003 ALOGW("FB is protected: PERMISSION_DENIED");
5004 return PERMISSION_DENIED;
5005 }
5006
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005007 // this binds the given EGLImage as a framebuffer for the
5008 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005009 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005010 if (bufferBond.getStatus() != NO_ERROR) {
5011 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005012 return INVALID_OPERATION;
5013 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005014
Dan Stozaabcda352017-06-01 14:37:39 -07005015 // this will in fact render into our dequeued buffer
5016 // via an FBO, which means we didn't have to create
5017 // an EGLSurface and therefore we're not
5018 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005019 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005020
Dan Stozaabcda352017-06-01 14:37:39 -07005021 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005022 getRenderEngine().finish();
5023 *outSyncFd = -1;
5024
chaviwa76b2712017-09-20 12:02:26 -07005025 const auto reqWidth = renderArea.getReqWidth();
5026 const auto reqHeight = renderArea.getReqHeight();
5027
Dan Stozaabcda352017-06-01 14:37:39 -07005028 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5029 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005030 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005031 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005032 } else {
5033 base::unique_fd syncFd = getRenderEngine().flush();
5034 if (syncFd < 0) {
5035 getRenderEngine().finish();
5036 }
5037 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005038 }
5039
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005040 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005041}
5042
Mathias Agopiand5556842013-09-19 17:08:37 -07005043void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005044 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005045 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005046 for (size_t y = 0; y < h; y++) {
5047 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5048 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005049 if (p[x] != 0xFF000000) return;
5050 }
5051 }
chaviwa76b2712017-09-20 12:02:26 -07005052 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005053
Robert Carr2047fae2016-11-28 14:09:09 -08005054 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005055 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005056 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005057 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5058 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5059 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5060 static_cast<float>(state.color.a));
5061 i++;
5062 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005063 }
5064}
5065
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005066// ---------------------------------------------------------------------------
5067
Dan Stoza412903f2017-04-27 13:42:17 -07005068void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5069 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005070}
5071
Dan Stoza412903f2017-04-27 13:42:17 -07005072void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5073 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005074}
5075
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005076void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5077 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005078 const LayerVector::Visitor& visitor) {
5079 // We loop through the first level of layers without traversing,
5080 // as we need to interpret min/max layer Z in the top level Z space.
5081 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005082 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005083 continue;
5084 }
5085 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005086 // relative layers are traversed in Layer::traverseInZOrder
5087 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005088 continue;
5089 }
5090 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005091 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005092 return;
5093 }
chaviwa76b2712017-09-20 12:02:26 -07005094 if (!layer->isVisible()) {
5095 return;
5096 }
5097 visitor(layer);
5098 });
5099 }
5100}
5101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005102}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005103
Chia-I Wu30505fb2018-03-26 16:20:31 -07005104
Mathias Agopian3f844832013-08-07 21:24:32 -07005105#if defined(__gl_h_)
5106#error "don't include gl/gl.h in this file"
5107#endif
5108
5109#if defined(__gl2_h_)
5110#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005111#endif